-1

I can receive a JSON file with variable number of nested fields, like for example this:

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

so that would be decoded as [String: [String: [String]]]

or could be:

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

so it would de decoded as [String: [String]], or could have one with even more nested levels ([String: [String: [String: [String]]]])... but I don´t know the structure I will receive in beforehand.

Is it possible to handle this scenario?

AppsDev
  • 12,319
  • 23
  • 93
  • 186

1 Answers1

0

Use Codable to get that working.

Model:

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

Parsing goes like,

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

The above code is a straight-forward parsing of any number of nested levels. Any specific model architecture will depend upon how are you using the model.

PGDev
  • 23,751
  • 6
  • 34
  • 88