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

时间:2018-12-02 09:37:08

标签: swift codable 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结果解码为动物属性为nil的Result

1 个答案:

答案 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)
    }
}