I need your help to implement a custom JSON decoding. The JSON returned by the API is:
{
"zones": [
{
"name": "zoneA",
"blocks": [
// an array of objects of type ElementA
]
},
{
"name": "zoneB",
"blocks": [
// an array of objects of type ElementB
]
},
{
"name": "zoneC",
"blocks": [
// an array of objects of type ElementC
]
},
{
"name": "zoneD",
"blocks": [
// an array of objects of type ElementD
]
}
]
}
I don’t want to parse this JSON as an array of zones with no meaning. I’d like to produce a model with an array for every specific type of block, like this:
struct Root {
let elementsA: [ElementA]
let elementsB: [ElementB]
let elementsC: [ElementC]
let elementsD: [ElementD]
}
How can I implement the Decodable
protocol (by using init(from decoder:)
) to follow this logic? Thank you.
2
Answers
This is a solution with nested containers. With the given (simplified but valid) JSON string
and the corresponding element structs
first decode the
zones
asnestedUnkeyedContainer
then iterate the array and decode first thename
key and depending onname
the elements.Side note: This way requires to declare the element arrays as
var
iables.Decoding the stuff is straightforward
the "zone" property is an array of
Zone
objects. so you can decode them like:Then you can filter out anything you like. For example you can pass in the array and get the result you asked in your question:
✅ Benefits: