iOS-使用动态密钥解码嵌套的JSON

时间:2019-01-20 09:51:09

标签: ios json swift

我正在尝试解码其中一个键更改的JSON:

[
{
    "id": "device:us-east-1",
    "serial": "eng031",
    "account": "9340370e",
    "name": "moti123",
    "tags": {
        "group": [
            "office"
        ]
    },
    "isAttached": true,
    "isShared": false
},
{
    "id": "lambda:device:us-east-1",
    "serial": "106",
    "account": "9340370e",
    "name": "roei106 ",
    "tags": {
        "comment": [
            "Iron Maiden "
        ]
    },
    "isAttached": true,
    "isShared": false
}
]

在这些示例中,您可以看到标记具有带有不同键的嵌套JSON: group 评论

我之前所做的非常简单。 我有这些结构:

public struct Device: Decodable {
  public init() {}

  public var id: String = ""
  public var serial: String = ""
  public var account: String = ""
  public var name: String = ""
  public var isAttached: Bool?
  public var isShared: Bool?
  public var tags: Tags?
 }

public struct Tags: Decodable {
  public init() {}

  public var comment: [String] = [""]
 }

我以前将它们解析如下:

   func getDevices(data: Data) -> [Device] {
    var devices = [Device]()

    do {
        let parsedModel = try JSONDecoder().decode([Device].self, from: data)
        devices = parsedModel
        print(parsedModel)
    } catch let error{
        print(error)
    }
    return devices
}

在标记中的键更改之前,一切都工作正常。 有什么办法知道什么是密钥并在tag结构中对其进行更改?

2 个答案:

答案 0 :(得分:0)

如您所见,Tags包含一个Dictionary,该字典具有String作为键,而String数组作为值。

因此您可以修改

public struct Tags: Decodable {
  public init() {}

  public var contents: [String:[String]]?
 }

答案 1 :(得分:0)

我建议使用此结构

typealias Scenarios = [Scenario]

struct YourJsonName: Codable {
    let id, serial, account, name: String
    let tags: Tags
    let isAttached, isShared: Bool
}

struct Tags: Codable {
    let group, comment: [String]?
}

如果需要初始化:

 public struct Tags: Decodable {
    public init() {}
    public var  comment: [String]? = nil
    public var  group: [String]? = nil
 }