1

我正在尝试制作继承的数据模型以便用JSONDecoder.

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

我将此 JSON 用于FirstClass

{
    "firstClassProperty":  123,
    "arrayOfInts": [
        123
    ]
}

这对于SecondClass

{
  "firstClassProperty": {},
  "secondClassProperty1": {},
  "secondClassProperty2": {}
}

如果关键字在这种情况下不起作用,我怎样才能摆脱arrayOfInts我的子类但让它在超类中?final

这里是游乐场。感谢您的回答!

4

2 回答 2

0

一个快速的技巧是将其声明为optional。例如:

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

这将自动解决丢失问题arrayOfInts

手动解决。另一种解决方案是自己实现Decodable协议——就像你在中所做的那样——并使用SecondClass解码(否则使用默认值)。arrayOfIntsdecodeIfPresent


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

...
let superDecoder = try container.superDecoder()
try super.init(from: superDecoder)
于 2017-10-17T00:49:05.280 回答
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)
    }
}
于 2017-10-17T00:59:24.027 回答