如何使用编码将包含动态对象的嵌套json密钥解码 [英] How to decode a nested json key which holds dynamic object using codable

查看:94
本文介绍了如何使用编码将包含动态对象的嵌套json密钥解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下格式的Web响应,问题是testMap是动态类型.对象的键以及数据类型是动态的. testMap将是一个字典类型的对象,它将在其动态键中包含动态数据.如您所见,它可以是字符串,字符串数组或整数数组.

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"]}}]
  }]
}

我试图使用此答案但它不起作用,因为在我的情况下,值类型未知. testMap:[String:Any]无效,原因是Any不符合Codable.

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.

模型

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
}

推荐答案

这将解码您的JSON:

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]?
}

而且,显然:

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

这篇关于如何使用编码将包含动态对象的嵌套json密钥解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆