Consider the following JSON:
{
"jsonName": "fluffy",
"color1": "Blue",
"color2": "Red",
"color3": "Green",
"color4": "Yellow",
"color5": "Purple"
}
And the model object:
struct Cat: Decodable {
let name: String
let colors: [String]
private enum CodingKeys: String, CodingKey {
case name = "jsonName"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
// How to parse all the items with colorX into the colors property???
}
}
There can be up to 10 colors, but some of them may be empty strings.
I’ve tried several variations of the decode
method but I can’t figure out how to use an identifier like color(i)
.
3
Answers
One simple but maybe not so elegant solution is to decode the json as a dictionary
and then add an init to the custom type that takes a dictionary as the argument
As with so many of these problems, the tool to start with is AnyCodingKey:
You can build this more simply, but this implementation is kind of nice.
With that, one possible decoder looks like this:
This decodes
"jsonName"
asname
, and then puts anything starting with"color"
intocolors
. You can adapt to a wide variety of specific use cases.try this simple approach using a
while
loop inside theinit(from decoder: Decoder)