简体   繁体   English

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

[英]Decoding empty JSON string value into nil with Decodable

Suppose I have a struct like this: 假设我有这样的结构:

struct Result: Decodable {
   let animal: Animal?
}

And an enum like this: 和这样的枚举:

enum Animal: String, Decodable {
   case cat = "cat"
   case dog = "dog"
}

but the JSON returned is like this: 但是返回的JSON是这样的:

{
  "animal": ""
}

If I try to use a JSONDecoder to decode this into a Result struct, I get Cannot initialize Animal from invalid String value as an error message. 如果我尝试使用JSONDecoder将其解码为Result结构,我得到Cannot initialize Animal from invalid String value中的Cannot initialize Animal from invalid String value为错误消息。 How can I properly decode this JSON result into a Result where the animal property is nil? 我怎样才能正确地解码此JSON结果到一个Result ,其中动物属性是零?

If you want to treat an empty string as nil , you need to implement your own decoding logic. 如果要将空字符串视为nil ,则需要实现自己的解码逻辑。 For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM