【问题标题】:SWIFT: Decode JSON object into structSWIFT:将 JSON 对象解码为结构
【发布时间】:2020-01-29 07:54:03
【问题描述】:

我正在尝试将 json 数据解析为可解码的结构。 我很困惑,因为我不知道如何在没有每个数组的键的情况下映射对象数组。 我拥有的json是:

{
    "table": [
        {
            "name": "Liverpool",
            "win": 22,
            "draw": 1,
            "loss": 0,
            "total": 67
        },
        {
            "name": "Man City",
            "win": 16,
            "draw": 3,
            "loss": 5,
            "total": 51
        }
    ]
}

这是我当前的结构:

struct Table: Decodable {
    let name: String
    let win: Int
    let draw: Int
    let loss: Int
    let total: Int
}

我只是想这样做:

    let tables = try! JSONDecoder().decode([Table].self, from: jsonData)

我得到的错误是:

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))

【问题讨论】:

    标签: json swift struct decode


    【解决方案1】:

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

    【讨论】:

    • try JSONDecoder().decode(Root.self, from: jsonData) 是我需要的,用我自己的结构替换Root.self。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2020-11-29
    • 2018-08-03
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多