假设我有一个这样的结构:
struct Result: Decodable {
let animal: Animal?
}
还有一个这样的枚举:
enum Animal: String, Decodable {
case cat = "cat"
case dog = "dog"
}
但是返回的JSON是这样的:
{
"animal": ""
}
如果尝试使用JSONDecoder
将其解码为Result
结构,则会收到Cannot initialize Animal from invalid String value
作为错误消息。我如何正确地将此JSON结果解码为动物属性为nil的Result
?
答案 0 :(得分:1)
如果要将空字符串视为nil
,则需要实现自己的解码逻辑。例如:
struct Result: Decodable {
let animal: Animal?
enum CodingKeys : CodingKey {
case animal
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let string = try container.decode(String.self, forKey: .animal)
// here I made use of the fact that an invalid raw value will cause the init to return nil
animal = Animal.init(rawValue: string)
}
}