【问题标题】:Swift json decode with dynamic keys使用动态键进行 Swift json 解码
【发布时间】:2019-10-27 04:58:03
【问题描述】:

我正在尝试使用动态键解码嵌套的 json,但找不到解决方案。 这是我的 json:

{
    "available_channels": {
        "1000": {
            "creation_date": "1111222",
            "category_id": "9"
        },
        "1001": {
            "creation_date": "222333",
            "category_id": "10"
        }
}

如您所见,“1000”和“1001”是动态的。

我正在使用的模型:

struct StreamsData: Codable{
    let availableChannels: AvailableChannels
}

struct AvailableChannels: Codable{
    let channels: [String: Channel]
}

struct Channel: Codable{
    let creationDate: String
    let categoryId: String
}

'StreamsData' 是根对象

'AvailableChannels'是包含所有通道对象的对象

'Channel'渠道模型

解码json:

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let streams = try decoder.decode(StreamsData.self, from: data)

使用这段代码我有这个错误:

CodingKeys(stringValue: "availableChannels", intValue: nil) - debugDescription : "没有与键 CodingKeys 关联的值(stringValue: \"channels\", intValue: nil) (\"channels\")。"

问题很明显,因为 'AvailableChannels' 被声明为具有 'channel' 属性,解码器正在尝试查找“channels”作为包含“creation_date”的对象的键。

你能帮我解决这个问题吗,谢谢。

【问题讨论】:

    标签: json swift decoder


    【解决方案1】:

    你只需要

    struct StreamsData: Codable{
        let availableChannels: [String: Channel]
    }
    
    struct Channel: Codable{
        let creationDate,categoryId: String 
    }
    

    do {
        let dec = JSONDecoder()
        dec.keyDecodingStrategy = .convertFromSnakeCase
        let res = try dec.decode(StreamsData.self, from: data)
    }
    catch { 
        print(error)
    }
    

    【讨论】:

    • 大声笑!我在发布后 1 分钟才发现这个!!但谢谢你:)
    • 为什么我们需要提供策略convertFromSnakeCase
    猜你喜欢
    • 1970-01-01
    • 2020-07-28
    • 2021-05-18
    • 2018-08-14
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多