0

I am trying to decode a JSON that one of the keys changes:

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

As you can see the tags has a nested JSON with different keys in these example: group and comment.

What I did before is pretty simple. I had these structs:

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

And I used to parse them as follow:

   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
}

It all have worked fine until the key in the tags changed. Is there any way to know what is the key and change it inside the tag struct?

Arash Etemad
  • 1,827
  • 1
  • 13
  • 29
ironRoei
  • 2,049
  • 24
  • 45

2 Answers2

0

As you can see Tags contains a Dictionary, that have String as key and Array of string as value.

So you can modify

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

  public var contents: [String:[String]]?
 }
Lal Krishna
  • 15,485
  • 6
  • 64
  • 84
0

I recomend use this struct

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

If you need init:

 public struct Tags: Decodable {
    public init() {}
    public var  comment: [String]? = nil
    public var  group: [String]? = nil
 }
E.Coms
  • 11,065
  • 2
  • 23
  • 35