解码子类时忽略超类属性

时间:2017-10-17 00:10:35

标签: ios json swift swift4 codable

我正在尝试创建继承的数据模型,以便用import requests, shutil from requests.exceptions import ReadTimeout, ConnectionError img_url = data['img'] filename = 'hello.jpg' try: response = requests.get(img_url, stream=True) with open(filename, 'wb') as img_file: shutil.copyfileobj(response.raw, img_file) except ReadTimeout: print("Connection timeout") except ConnectionError: print("Connection refused") 解析它。

JSONDecoder

我将此JSON用于class FirstClass : Codable { let firstClassProperty: Int final let arrayOfInts: [Int] } class SecondClass : FirstClass { let secondClassProperty1: Int let secondClassProperty2: Int private enum CodingKeys : String, CodingKey { case secondClassProperty1, secondClassProperty2 } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) secondClassProperty1 = try container.decode(Int.self, forKey: .secondClassProperty1) secondClassProperty2 = try container.decode(Int.self, forKey: .secondClassProperty2) try super.init(from: decoder) } }

FirstClass

这适用于{ "firstClassProperty": 123, "arrayOfInts": [ 123 ] }

SecondClass

如果我的子类中除了{ "firstClassProperty": {}, "secondClassProperty1": {}, "secondClassProperty2": {} } ,但如果关键字arrayOfInts在这种情况下不起作用,那么让它在超类中?

这是HERE。谢谢你的回答!

2 个答案:

答案 0 :(得分:0)

快速破解是将其声明为可选。例如:

class FirstClas: Codable {
    let firstClassProperty: Int
    final let arrayOfInts: [Int]?
}

这会自动解决丢失的arrayOfInts

手动解决方案。另一种解决方案是自己实施Decodable协议 - 就像在SecondClass中一样 - 并使用decodeIfPresent解码arrayOfInts(否则使用默认值)。

超类解码。顺便说一句,将Decoder转发给超类的推荐方法是使用superDecoder()方法:

...
let superDecoder = try container.superDecoder()
try super.init(from: superDecoder)

答案 1 :(得分:0)

您可以这样使用:

class FirstClass : Codable {
    let firstClassProperty: Int
    final let arrayOfInts: [Int]?
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        firstClassProperty = try container.decode(Int.self, forKey: .firstClassProperty)
        arrayOfInts = try container.decodeIfPresent([Int].self, forKey: .arrayOfInts)
    }
}