2017-10-13 3 views
4

안녕하세요, API 구조에서 더 중첩 된 다음 구조를 중첩했지만이 부분을 인코딩/디코딩 할 수 없습니다. 내가 겪고있는 문제는 customKey와 customValue가 모두 동적이라는 것입니다. 동적 유형/객체에 Codable 사용

{ 
    "current" : "a value" 
    "hash" : "some value" 
    "values": { 
     "customkey": "customValue", 
     "customKey": "customValue" 
    } 
} 

나는 var values: [String:String]처럼 뭔가를 시도하지만 그 작업 분명하지 않다 [String:String]의 그것 실제로 배열 때문이다.

+0

@vadian 나는이 그 중 어느 중복 표시되지 않습니다 질문. 나는이 질문을 지금보다 분명하게 수정했다. – Reshad

+0

질문을 이해하고 다시 엽니 다. 짧은 대답 : 동적 키와 함께 '코드 가능'을 사용할 수 없습니다. – vadian

+0

다른 방법으로이 작업을 수행 할 것을 권장 할 수 있습니까? – Reshad

답변

6

다른 질문에 대한 내 대답에 연결 했으므로 답변을 확장하여 귀하의 대답에 적용 할 것입니다. 당신이 보는 위치를 알고있는 경우에

진리는 모든 키가 런타임에 알려져있다 :

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) 
+0

빠른 응답을 보내 주셔서 감사합니다. JSON에서 일반적인 디코딩 가능한 값 옆에 다른 키가있는 경우 어떻게 적용할까요? 일반 enum 컨테이너를 추가합니까? – Reshad

+0

새로운 요구 사항과 혼동스러워하고 있습니다. 예를 보여주기 위해 JSON을 편집 할 수 있습니까? –

+0

JSON을 편집했습니다. 내가 의미하는 바는 인코딩과 디코딩을하는 실제 객체가 키 -> 객체 값 이상을 가졌다는 것입니다. :) – Reshad