I am trying to parse json data into a decodable struct. I am confused because I don't know how to map the array of objects without a key for each array. The json I have is:
{
"table": [
{
"name": "Liverpool",
"win": 22,
"draw": 1,
"loss": 0,
"total": 67
},
{
"name": "Man City",
"win": 16,
"draw": 3,
"loss": 5,
"total": 51
}
]
}
Here us my current struct:
struct Table: Decodable {
let name: String
let win: Int
let draw: Int
let loss: Int
let total: Int
}
I'm just trying to do something like:
let tables = try! JSONDecoder().decode([Table].self, from: jsonData)
The error I get is:
Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "name", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"name\", intValue: nil) (\"name\").", underlyingError: nil))
You are ignoring the root object, the dictionary with key table
struct Root: Decodable {
let tables : [Table]
enum CodingKeys : String, CodingKey { case tables = "table" }
}
struct Table: Decodable {
let name: String
let win: Int
let draw: Int
let loss: Int
let total: Int
}
do {
let result = try JSONDecoder().decode(Root.self, from: jsonData)
let tables = result.tables
} catch { print(error) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With