如何使用codable解码包含动态对象的嵌套json密钥

时间:2018-03-08 19:42:24

标签: ios json swift codable

我收到以下格式的网页回复,问题是testMap属于动态类型。对象的键以及数据类型是动态的。 testMap将是一个字典类型对象,它将在其动态密钥中包含动态数据。如您所见,它可以是字符串,字符串数组或整数数组。

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

我尝试use this answer但是它不起作用,因为我的情况下值类型未知。 testMap:[String:Any]无效,因为Any不符合Codable

模型

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 个答案:

答案 0 :(得分:0)

这将解码您的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]?
}

显然:

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