繁体   English   中英

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

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

我有如下的json负载

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

我想从json转换为自定义类型的类如下

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

解码过程:

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!")

动物对象为零。 但是根据苹果的WWDC演讲( https://developer.apple.com/videos/play/wwdc2017/212/ ),它应该为type属性将值分配为nil。 由于“类型”数据不匹配。 (期望的字符串,但已找到整数)

您能猜出其背后的原因是什么。 如果任何一种标签数据类型不匹配,则整个对象变为零对我来说听起来并不好。

请仔细阅读错误消息,原因很明确(无需猜测

预期的字符串,但已找到Int

表示(找到的)值是Int但是您声明了String属性

JSON中的所有字符串都用双引号引起来,类型的typeInt

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

如果JSON始终包含两个值,则通过删除问号将属性声明为非可选属性。

如果发生任何错误,则隐式解码器/初始化器将失败,您可以仅从代码语法中看到这一点。 如果想要更好的控制,请编写自己的自定义初始化程序。

仅对类型不匹配的属性获取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