All questions I have found so far on the searches I've done is about decoding nested JSON to some struct with nested properties. I want to do the opposite: decode flat JSON to a struct with nested properties.
Here's example JSON:
{
"id":"ABC123",
"cell":"test",
"qty":24
}
which I'd like to decode to this struct:
struct InventoryItem {
let id: String
let mfgInfo: MfgInfo
}
extension InventoryItem {
struct MfgInfo {
let cell: String
let qty: Int
}
}
I have tried adding CodingKeys for each struct:
struct InventoryItem: Decodable {
let id: String
let mfgInfo: MfgInfo
enum CodingKeys: String, CodingKey {
case id, mfgInfo
}
}
struct MfgInfo: Decodable {
let cell: String
let qty: Int
enum CodingKeys: String, CodingKey {
case cell, qty
}
}
But this doesn't work. I get this error:
No value associated with key CodingKeys(stringValue: \"mfgInfo\", intValue: nil) (\"mfgInfo\"), converted to mfg_info.
How can I make this work without a custom initializer? Or do I need to write a custom init(with: Decoder) initializer?