2017-10-13 47 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

我明白並重新提出了這個問題:簡短的回答:你不能在動態密鑰中使用'Codable'。 – 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中有其他鍵可以正常解碼的值旁邊,這將如何應用,我是否添加了一個正常的枚舉容器? – Reshad

+0

我對你的新要求感到困惑。你能編輯JSON來展示它的一個例子嗎? –

+0

我編輯了JSON。我的意思是,我編碼和解碼的實際對象不僅僅是值 - 鍵 - >對象。 :) – Reshad