Given the JSON:
[{
"name": "TV",
"room": "Living Room"
},
{
"name": "LightBulb 1",
"room": "Living Room"
}
]
struct Room: Decodable {
let name: String
let devices: [Device]
}
struct Device: Decodable {
let name: String
}
How can I use the Swift 4 Decodable way of decoding JSON get my model structure correctly serialized? I want to make rooms for every unique string in the room
attribute of a device, and add those devices to the device list of that given room.
One way is simply to map this without the room relation and then parse that relation after i have gotten the whole list of Devices, with just running through and creating rooms on demand as i iterate it. But that does not feel like The Swift 4™
way of doing it. Is there a smarter way?
I'm making an assumption here - that by "the Swift 4 Decodable way of decoding JSON" you mean calling
try JSONDecoder().decode([Room].self, from: jsonData)
. If that's the case then, to my knowledge, you're out of luck since theJSONDecoder
will iterate through its parsed JSON objects and call the initializerRoom(from: Decoder)
on each. Even if you were to create your own initializer, it would have no way of knowing what the other JSON objects contained.One way to solve this could be by creating an intermediate
Decodable
struct reflecting each JSON object's properties, and then create yourRoom
s by going through an array of these structs.Here's an example, works fine as an Xcode playground:
Or - maybe an even more Swift4'y way of doing this:
Note - I've used
try?
a few times in the code above. Obviously you should handle errors properly - theJSONDecoder
will give you nice, specific errors depending on what went wrong! :)