【问题标题】:How to decode a nested JSON struct with dynamic number of nested levels?如何解码具有动态嵌套级别数的嵌套 JSON 结构?
【发布时间】:2019-12-14 21:34:02
【问题描述】:

我可以收到一个包含可变数量嵌套字段的 JSON 文件,例如:

{
 "id": "field1",
 "values": [{
  "1": [{ 
    "11": ["111", "112"],
    "12": ["121", "122"]
  }],
  "2": [{ 
    "21": ["211", "212"],
    "22": ["221", "222"]
  }]
]
}

所以它会被解码为[String: [String: [String]]]

或者可能是:

{
 "id": "field1",
 "values": [{
    "1": ["11", "12"],
    "2": ["21", "22"]
  }]
}

所以它会解码为[String: [String]],或者可以有一个具有更多嵌套级别 ([String: [String: [String: [String]]]])...但我不知道我会事先收到的结构。

这种情况可以处理吗?

【问题讨论】:

  • 您添加的 JSON 格式不正确。
  • 解析后如何在代码库中使用values

标签: ios json swift swift4 codable


【解决方案1】:

使用 Codable 来实现。

型号:

struct Root: Codable {
    let id: String
    let values: [[String:[[String:[String]]]]]
}

解析就像,

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

上面的代码是对任意数量的嵌套级别的直接解析。任何特定的模型架构都将取决于您如何使用该模型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2015-01-15
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多