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

2
  • The JSON you added is not in the correct format.
    – PGDev
    Commented Aug 7, 2019 at 9:34
  • How would you use such values in your code base once parsed?
    – denis_lor
    Commented Aug 7, 2019 at 9:36

1 Answer 1

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.