【发布时间】: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”的对象的键。
你能帮我解决这个问题吗,谢谢。
【问题讨论】: