I have a weird json which is basically an array of objects, where each object should be decoded as a separate type. I've managed to get it working by iterating the json with two iterators. the first iterator is used to decide what type should be used for decoding. The second iterator does the actual decoding. i feel like i'm missing something because it shouldn't be neccessary to create two iterators. this is my code:
import Foundation
struct JSONArray: Decodable {
let a: [A]
let b: [B]
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var container1 = try decoder.unkeyedContainer()
var aArray: [A] = []
var bArray: [B] = []
while !container.isAtEnd {
let nestedContainer = try container.nestedContainer(keyedBy: CodingKeys.self)
if nestedContainer.contains(.a) {
aArray.append(try container1.decode(A.self))
} else if nestedContainer.contains(.b) {
bArray.append(try container1.decode(B.self))
}
}
a = aArray
b = bArray
}
private enum CodingKeys: String, CodingKey {
case a
case b
}
}
struct A: Decodable {
let a: String
}
struct B: Decodable {
let b: String
}
let json = """
[
{
"a": "abc"
},
{
"a": "def"
},
{
"b": "def"
}
]
"""
guard let data = json.data(using: .utf8) else { fatalError() }
let decoded = try! JSONDecoder().decode(JSONArray.self, from: data)
print(decoded)
i know that the provided example is super simple and it could be solved with optionals, but the problem i'm actually trying to solve has to be solved in this way.