Swift json 使用动态密钥解码

Swift json decode with dynamic keys

我正在尝试使用动态密钥解码嵌套的 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 : "No value associated with key CodingKeys(stringValue: \"channels\", intValue: nil) (\"channels\")."

问题很明显,因为 'AvailableChannels' 被声明为 'channel' 属性,解码器试图找到 "channels" 作为包含"creation_date".

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

你只需要

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