How to decode a nested json key which holds dynamic object using codable

时间秒杀一切 提交于 2019-12-13 03:16:47

问题


I am getting some web response in the below format, The problem is testMap is of dynamic type. Key of the object as well as the data type is dynamic. testMap will be a dictionary type object, which'll contain dynamic data in its dynamic key. As you can see, it can be string, array of string or array of integers.

{"results": [
  {"tests": [{
        "testsType": "A",
        "testMap": {
          "testId": "5a7c4fedec7fb72b7aa9b36e"}}]
  },
  {
    "tests": [{
        "testsType": "B",
        "testMap": {
          "myIds": ["2112"]}}]
  }]
}

I tried to use this answer but It didn't work cause the value type is unknown in my case. testMap:[String:Any] didn't work, cause Any doesn't conform to Codable.

Model

struct Results: Codable
{
 let results: [Tests]
}
 struct Tests: Codable
{
 let tests: [Test]
}
 struct Test: Codable
{
 let testsType: String?
 var testMap:[String:String] // Its wrong, cause value type is unknown
}

回答1:


This will decode your JSON:

struct Results: Codable {
    let results: [Tests]
}

struct Tests: Codable {
    let tests: [Test]
}

struct Test: Codable {
    let testsType: String
    let testMap: TestMap
}

struct TestMap: Codable {
    let testId: String?
    let myIds: [String]?
}

And, obviously:

do {
    let result = try JSONDecoder().decode(Results.self, from: data)
    print(result)
} catch {
    print(error)
}


来源:https://stackoverflow.com/questions/49181230/how-to-decode-a-nested-json-key-which-holds-dynamic-object-using-codable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!