Using Codable on a dynamic type/object

前端 未结 2 372
南方客
南方客 2020-12-03 05:54

Hi I have the following structure nested in a bigger structure that is returned from an api call but I can\'t manage to encode/decode this part. The problem I am having is t

2条回答
  •  一整个雨季
    2020-12-03 06:47

    Simplified answer, it is working with dictionary [String: String] (instatead of String you can use other struct):

    let jsonData = """
    {
        "current": "a value",
        "hash": "a value",
        "values": {
            "key1": "customValue",
            "key2": "customValue"
        }
    }
    """.data(using: .utf8)!
    
    struct MyModel: Decodable {
        var current: String
        var hash: String
        var values: [String: String]
    }
    
    let model = try JSONDecoder().decode(MyModel.self, from: jsonData)
    
    for (key,value) in model.values {
        print("key: \(key) value: \(value)")
    }
    

提交回复
热议问题