The problem is merely that your structs look nothing at all like your JSON!
Your JSON is a dictionary whose keys have names like "-8802586561990153106-1804221538-5"
and "8464567322535526441-1804221546-15"
. But I don’t see you declaring any struct that deals with those keys.
Then each of those turns out to be a dictionary with keys like "zug"
, "ankunft"
, and "abfahrt"
. But I don’t see you declaring any struct that deals with those keys either.
And then the "zug"
has keys "klasse"
and "nummer"
; you don’t have those either.
And so on.
Either your structs must look exactly like your JSON, or else you must define CodingKeys and possibly also implement init(from:)
to deal with any differences between your structs and your JSON. I suspect that the keys "-8802586561990153106-1804221538-5"
and "8464567322535526441-1804221546-15"
are unpredictable, so you will probably have to write init(from:)
in order to deal with them.
For example, I was able to decode your JSON like this (I do not really recommend using try!
, but we decoded without error and it’s just a test):
struct Entry : Codable {
let zug : Zug
let ankunft : AnkunftAbfahrt
let abfahrt : AnkunftAbfahrt
}
struct Zug : Codable {
let klasse : String
let nummer : String
}
struct AnkunftAbfahrt : Codable {
let zeitGeplant : String
let zeitAktuell : String
let routeGeplant : [String]
}
struct Top : Decodable {
var entries = [String:Entry]()
init(from decoder: Decoder) throws {
struct CK : CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int?
init?(intValue: Int) {
return nil
}
}
let con = try! decoder.container(keyedBy: CK.self)
for key in con.allKeys {
self.entries[key.stringValue] =
try! con.decode(Entry.self, forKey: key)
}
}
}
// d is a Data containing your JSON
let result = try! JSONDecoder().decode(Top.self, from: d)
2
solved Parse complex json code