How can I implement a solution where I could set the type of a parameter on the go while parsing a JSON by analyzing the parameter at the same level as the other parameter?
let sampleData = Data("""
[
{
"type": "one",
"body": {
"one": 1
},
.
.
.
},
{
"type": "two",
"body": {
"two": 2,
"twoData": "two"
},
.
.
.
}
]
""".utf8)
struct MyObject: Codable {
let type: String
let body: Body
}
struct Body: Codable {
let one, two: Int?
let twoData: String?
}
print(try JSONDecoder().decode([MyObject].self, from: sampleData))
Here you can see that the keys in Body
are all optionals. My solution requires they being parsed into different types according to the value given in the parameter type
. How can I parse body into the following 2 separate types according to the value I receive in type
?
struct OneBody: Decodable {
let one: Int
}
struct TwoBody: Decodable {
let two: Int
let twoData: String
}