다른 질문에 대한 내 대답에 연결 했으므로 답변을 확장하여 귀하의 대답에 적용 할 것입니다. 당신이 보는 위치를 알고있는 경우에
진리는 모든 키가 런타임에 알려져있다 :
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
질문을 이해하고 다시 엽니 다. 짧은 대답 : 동적 키와 함께 '코드 가능'을 사용할 수 없습니다. – vadian
다른 방법으로이 작업을 수행 할 것을 권장 할 수 있습니까? – Reshad