У меня есть API, который иногда возвращает определенный ключ (в этом случае id
) в JSON как Int, а в других случаях он возвращает тот же самый ключ, что и String. Как использовать кодируемый для анализа JSON?
struct GeneralProduct: Codable {
var price:Double!
var id:String?
var name:String!
private enum CodingKeys: String, CodingKey {
case price = "p"
case id = "i"
case name = "n"
}
init(price:Double? = nil, id: String? = nil, name: String? = nil) {
self.price = price
self.id = id
self.name = name
}
}
Я продолжаю получать это сообщение об ошибке: Expected to decode String but found a number instead
. Причина, по которой он возвращает число, состоит в том, что поле id пустое, а когда поле id пусто, оно по умолчанию возвращает 0 в качестве идентификатора, который кодируемый идентифицирует как число. Я могу в принципе игнорировать ID-ключ, но способный код не дает мне возможность игнорировать его, насколько мне известно. Какой был бы лучший способ справиться с этим?
Вот JSON. Это супер просто
За работой
{
"p":2.12,
"i":"3k3mkfnk3",
"n":"Blue Shirt"
}
Ошибка - потому что в системе нет идентификатора, она возвращает 0 как значение по умолчанию, которое, по-видимому, воспринимается как число, противоположное строке.
{
"p":2.19,
"i":0,
"n":"Black Shirt"
}