Codable
当您了解 JSON 数据的关键格式时,这会非常有用。但是如果您不知道密钥怎么办?我目前面临这个问题。
通常我希望 JSON 数据像这样返回:
{
"id": "<123>",
"data": [
{
"id": "<id1>",
"event": "<event_type>",
"date": "<date>"
},
{
"id": "<id2>",
"event": "<event_type>",
"date": "<date>"
},
]
}
但这就是我想要解码的:
{
"id": "123",
"data": [
{ "<id1>": { "<event>": "<date>" } },
{ "<id2>": { "<event>": "<date>" } },
]
}
问题是:我该如何使用Codable
解码 JSON,其中键是唯一的?我觉得我错过了一些明显的东西。
这就是我希望做的,这样我就可以使用Codable
:
struct SampleModel: Codable {
let id: String
let data: [[String: [String: Any]]]
// MARK: - Decoding
enum CodingKeys: String, CodingKey {
case id = "id"
case data = "data"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
// This throws an error: Ambiguous reference to member 'decode(_:forKey:)'
data = try container.decode([[String: [String: Any]]].self, forKey: .data)
}
}
这会引发错误:Ambiguous reference to member 'decode(_:forKey:)'