Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWIFT: Decode JSON object into struct

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))
like image 638
brados Avatar asked Jul 09 '26 12:07

brados


1 Answers

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) }
like image 67
vadian Avatar answered Jul 11 '26 10:07

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!