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

Decoding empty JSON string value into nil with Decodable

假设我有这样一个结构:

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 结果解码为 Result,其中动物 属性 为零?

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