I am currently trying to parse a nested dictionary response using Codable and trying to not use too much custom decoders.
JSON response looks similar to below:
{
"id": "1234",
"data": {
"1": {
"name": "foo1",
"types": {
"a": {
"value": "bar1"
},
"b": {
"value": "bar2"
},
"c": {
"value": "bar3"
}
}
},
"2": {
"name": "foo2",
"types": {
"d": {
"value": "bar4"
},
"e": {
"value": "bar5"
},
"f": {
"value": "bar6"
}
}
}
}
}
Root Class
struct JSONResponse : Codable {
let id : String?
let data : Data?
enum CodingKeys: String, CodingKey {
case id = "id"
case data = "data"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decodeIfPresent(String.self, forKey: .id)
data = try values.decodeIfPresent(Data.self, forKey: .data)
}
}
Now the data class is where I would end up with many nested containers. Is there any better way to resolve this ?
5