Hello people I have a little question related with the Encodable protocol in Swift.
I have the following json file:
let magicJson = """
{
"value": [
{
"scheduleId": "[email protected]",
"somethingEventMoreMagical": "000220000"
}
]
}
""".data(using: .utf8)!
For decoding I tried to avoid having to create two objects that both go with Decodable, and the first one has an array of the second object. I would like to flatten that object into something like this:
struct MagicalStruct: Decodable {
private enum CodingKeys: String, CodingKey {
case value
}
private enum ScheduleCodingKeys: String, CodingKey {
case roomEmail = "scheduleId"
}
let roomEmail: String
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let magicContainer = try container.nestedContainer(keyedBy: ScheduleCodingKeys.self, forKey: .value)
roomEmail = try magicContainer.decode(String.self, forKey: ScheduleCodingKeys.roomEmail)
}
}
However when I try the following code: JSONDecoder().decode(MagicalStruct.self, magicJson) I get that it expects an array but gets a dictionary. On the other hand when I go with JSONDecoder().decode([MagicalStruct].self, magicJson), I get that it receives an array but expects a dictionary.
Does anyone know why this is happening ?
scheduleIdkey in your input JSON.