简体   繁体   English

SWIFT:将 JSON 对象解码为结构体

[英]SWIFT: Decode JSON object into struct

I am trying to parse json data into a decodable struct.我正在尝试将 json 数据解析为可解码的结构。 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:我拥有的 json 是:

{
    "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您忽略了根对象,即带有键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) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM