简体   繁体   English

为什么在swift4中的Decode方法给对象nil如果json负载中有一个标签类型不匹配

[英]why Decode method in swift4 gives object nil if there is one tag in json payload has type mismatch

I've json payload as below 我有如下的json负载

{
    "name": "Dog",
    "type": 1
}

and the class which I want to convert from json to custom type is as below 我想从json转换为自定义类型的类如下

class Animal: Codable {
      var name: String?
      var type: String?
}

Decoding process: 解码过程:

let decoder = JSONDecoder()
        var animal: Animal?

        do {
            animal = try decoder.decode(Animal.self, from: data)
        } catch DecodingError.keyNotFound(let key, let context) {

        } catch DecodingError.valueNotFound(let type, let context) {

        } catch DecodingError.typeMismatch(let type, let context) {
            print("mismatch")
        }
        catch {
            print("some error \(error.localizedDescription)")
        }

        print(animal?.name ?? "Decode did not happen!")

Animal object is nil. 动物对象为零。 However as per apple WWDC talk( https://developer.apple.com/videos/play/wwdc2017/212/ ) it supposed to assign value to nil for type property. 但是根据苹果的WWDC演讲( https://developer.apple.com/videos/play/wwdc2017/212/ ),它应该为type属性将值分配为nil。 Since there is a mismatch in "type" data. 由于“类型”数据不匹配。 (Expected String but Int has been found) (期望的字符串,但已找到整数)

Can you guess what is the reason behind this. 您能猜出其背后的原因是什么。 If any one of the tag data type is mismatched then whole object is becoming nil doesn't sounds good to me. 如果任何一种标签数据类型不匹配,则整个对象变为零对我来说听起来并不好。

Please read the error message carefully, the reason is very clear (no need to guess ) 请仔细阅读错误消息,原因很明确(无需猜测

Expected String but Int has been found 预期的字符串,但已找到Int

means the (found) value is Int but you declared a String property 表示(找到的)值是Int但是您声明了String属性

All strings in JSON are wrapped in double quotes, the type for type is Int JSON中的所有字符串都用双引号引起来,类型的typeInt

class Animal: Codable {
    var name: String?
    var type: Int?
}

If the JSON contains always both values declare the properties as non-optional by removing the question marks. 如果JSON始终包含两个值,则通过删除问号将属性声明为非可选属性。

The implicit decoder / initializer fails if any error occurs, you can see this just from the code syntax. 如果发生任何错误,则隐式解码器/初始化器将失败,您可以仅从代码语法中看到这一点。 If you want to have finer control write your own custom initializer. 如果想要更好的控制,请编写自己的自定义初始化程序。

To get nil only for type mismatched property : 仅对类型不匹配的属性获取nil

required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    name = (try? container.decodeIfPresent(String.self, forKey: .name)) ?? nil
    type = (try? container.decodeIfPresent(String.self, forKey: .type)) ?? nil
}

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

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