I have been struggling to develop a code to decode multiple different JSON strings into a combined data structure (struct).
As you can see in the code below, the two JSON strings correctInput and faultyInput, contain the same values but the key has a different name.
Is there a way to decode such different strings (2 or more) into a common Codable struct?
Thank you!
import Foundation
struct Fruit: Codable, Equatable {
var apple: String
var banana: String
var pineapple: String
}
let correctInput = """
{
"apple": "Akane",
"banana": "Bria",
"pineapple": "Sarawak"
}
""".data(using: .utf8)!
let faultyInput = """
{
"appl": "Akane",
"nana": "Bria",
"pine": "Sarawak"
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let correctFruit = try? decoder.decode(Fruit.self, from: correctInput)
let faultyFruit = try? decoder.decode(Fruit.self, from: faultyInput)
print(correctFruit)
print(faultyFruit)
faultyInputalways has the same keys. What do you mean withinit(from:)? - GatCodeapplto fill the the stuct, but not how I can fill the stuct with bothapplandapple. Or more complicated: Theapplevar in theFruitstruct should be filled with eitherapplorappleora- GatCode