由於您鏈接到我對另一個問題的回答,因此我將擴展該答案以回答您的問題。
事實是,所有的按鍵都在運行時知道,如果你知道去哪裏找:
struct GenericCodingKeys: CodingKey {
var intValue: Int?
var stringValue: String
init?(intValue: Int) { self.intValue = intValue; self.stringValue = "\(intValue)" }
init?(stringValue: String) { self.stringValue = stringValue }
static func makeKey(name: String) -> GenericCodingKeys {
return GenericCodingKeys(stringValue: name)!
}
}
struct MyModel: Decodable {
var current: String
var hash: String
var values: [String: String]
private enum CodingKeys: String, CodingKey {
case current
case hash
case values
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
current = try container.decode(String.self, forKey: .current)
hash = try container.decode(String.self, forKey: .hash)
values = [String: String]()
let subContainer = try container.nestedContainer(keyedBy: GenericCodingKeys.self, forKey: .values)
for key in subContainer.allKeys {
values[key.stringValue] = try subContainer.decode(String.self, forKey: key)
}
}
}
用法:
let jsonData = """
{
"current": "a value",
"hash": "a value",
"values": {
"key1": "customValue",
"key2": "customValue"
}
}
""".data(using: .utf8)!
let model = try JSONDecoder().decode(MyModel.self, from: jsonData)
@vadian我不明白這是怎麼複製的任何這些的問題。我現在把這個問題修改得更清楚了。 – Reshad
我明白並重新提出了這個問題:簡短的回答:你不能在動態密鑰中使用'Codable'。 – vadian
你能推薦另一種方法來做到這一點? – Reshad