如何解码 Swift 中继承的 类 数组

How to decode an array of inherited classes in Swift

问题:解码属于 Parent 和 Child classes.

的对象数组

我阅读了很多关于这个主题的资料,但一直找不到简单的解决方案。

我编码了一个类型 属性,它提供了原始 class 的信息,但我还没有找到在解码对象时使用它的方法。

class Parent: Codable, CustomDebugStringConvertible {
    var debugDescription: String {
        return "[\(name)]"
    }
    
    var name: String
    init(name: String) {
        self.name = name
    }
    
    enum CodingKeys: CodingKey {
        case name
        case type
        case age
    }
    
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try! container.decode(String.self, forKey: .name)
        let type = try! container.decode(String.self, forKey: .type)
        print("Reading \(type)")
        
        if type == "Child" {
            try Child.init(from: decoder)
            return
        }
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode("Parent", forKey: .type)
        try container.encode(name, forKey: .name)
    }
}


class Child: Parent {
    
    override var debugDescription: String {
        return "[\(name) - \(age)]"
    }
    var age: Int

    init(name: String, age: Int) {
        self.age = age
        super.init(name: name)
    }
    
    enum CodingKeys: CodingKey {
        case name
        case age
        case type
    }
    
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        age = try! container.decode(Int.self, forKey: .age)
        let name = try! container.decode(String.self, forKey: .name)
        super.init(name: name) // I think the problem is here!
    }
    
    override func encode(to encoder: Encoder) throws {
        try super.encode(to: encoder)
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode("Child", forKey: .type)
        try container.encode(age, forKey: .age)
    }
}

这是测试代码。


let array = [Parent(name: "p"), Child(name: "c",age: 2)]
print(array)
        
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let decoder = JSONDecoder()
do {
   let jsonData = try encoder.encode(array)
   let s = String(data: jsonData, encoding: .ascii)
   print("Json Data \(s!)")
            
    let decodedArray = try decoder.decode([Parent].self, from: jsonData)
            
    print(decodedArray)
 }
 catch {
    print(error.localizedDescription)
 }

原数组的输出为:

[[p], [c - 2]]

解码数组的输出为:

[[p], [c]]

如何更改 Parent and/or Child 初始化函数以正确解码对象?

显然,我的实际情况要复杂得多。我必须对 class 进行编码/解码,其中包含具有继承性的 classes 数组。我试过用这个:

https://github.com/IgorMuzyka/Type-Preserving-Coding-Adapter

显然,它在父子数组上工作正常,但如果数组在另一个 class.

中则不行

此外,我想学习一种在其他情况下重用的解决方案,避免包含不是严格需要的外部库。

我认为问题的主要部分是您正在使用混合类型数组 [Any],然后将其解码为一种父类型,因为很有可能将子对象设为正确编码为 Child.

一个解决方案是创建一个新的 Codable 结构来保存数组,并使用 type 属性 跟踪如何解码对象数组

enum ObjectType: String, Codable {
    case parent
    case child
}

struct ParentAndChild: Codable {
    let objects: [Parent]

    enum CodingKeys: CodingKey {
        case objects
    }

    enum ObjectTypeKey: CodingKey {
        case type
    }

    init(with objects: [Parent]) {
        self.objects = objects
    }

    init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            var objectsArray = try container.nestedUnkeyedContainer(forKey: CodingKeys.objects)
            var items = [Parent]()

        var array = objectsArray
        while !objectsArray.isAtEnd {
            let object = try objectsArray.nestedContainer(keyedBy: ObjectTypeKey.self)
            let type = try object.decode(ObjectType.self, forKey: ObjectTypeKey.type)
            switch type {
            case .parent:
                items.append(try array.decode(Parent.self))
            case .child:
                items.append(try array.decode(Child.self))
            }
        }
        self.objects = items
    }
}

我也对 classes 进行了一些更改,Parent class 得到了极大的简化,Child class 修改了 encoding/decoding 的功能,其中主要变化是 init(from:) 调用超级 init(from:)

class Parent: Codable, CustomDebugStringConvertible {
    var debugDescription: String {
        return "[\(name)]"
    }

    var name: String
    init(name: String) {
        self.name = name
    }
}

class Child: Parent {

    override var debugDescription: String {
        return "[\(name) - \(age)]"
    }
    var age: Int

    init(name: String, age: Int) {
        self.age = age
        super.init(name: name)
    }

    enum CodingKeys: CodingKey {
        case age
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        age = try container.decode(Int.self, forKey: .age)
        try super.init(from: decoder)
    }

    override func encode(to encoder: Encoder) throws {
        try super.encode(to: encoder)
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(age, forKey: .age)
    }
}