Swift 使用Decodable将空JSON字符串值解码为nil

Swift 使用Decodable将空JSON字符串值解码为nil,swift,codable,decodable,Swift,Codable,Decodable,假设我有这样一个结构: struct Result: Decodable { let animal: Animal? } enum Animal: String, Decodable { case cat = "cat" case dog = "dog" } { "animal": "" } 还有这样的枚举: struct Result: Decodable { let animal: Animal? } enum Animal: String, Decoda

假设我有这样一个结构:

struct Result: Decodable {
   let animal: Animal?
}
enum Animal: String, Decodable {
   case cat = "cat"
   case dog = "dog"
}
{
  "animal": ""
}
还有这样的枚举:

struct Result: Decodable {
   let animal: Animal?
}
enum Animal: String, Decodable {
   case cat = "cat"
   case dog = "dog"
}
{
  "animal": ""
}
但返回的JSON如下所示:

struct Result: Decodable {
   let animal: Animal?
}
enum Animal: String, Decodable {
   case cat = "cat"
   case dog = "dog"
}
{
  "animal": ""
}

如果我尝试使用
JSONDecoder
将其解码为
结果
结构,我会得到
无法从无效字符串值初始化动物的错误消息。如何正确地将此JSON结果解码为
结果
,其中动物属性为nil

如果要将空字符串视为
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)
    }
}

在您的例子中,JSON中的animal不是nil。两者都不是动物型。它是字符串类型。它只是一个空字符串。