当 super class 也是 Codable 时,如何在 sub-class 中使用 CodingKeys?

How to use CodingKeys in sub-class when the super class is also Codable?

我正在研究JSON编码和解码,但有些问题很烦人,我不知道如何在inherit classes中使用CodingKeys

我有两个 classes ResponseBeanResponseWithObjectBean<T>

这是响应 class 定义:

public class ResponseBean: Codable
{
    //This is only sample, I define `CodingKeys` because the property in json is in different name.
    private enum CodingKeys: String, CodingKey
    {
        case intA
        case intB
    }
    public var intA: Int32 = 0
    public var intB: Int32 = 0

}

public class ResponseWithObjectBean<T: Codable> : ResponseBean
{
    /*
    Here I don't know how to define an enum to confirm protocl CondingKey. 
    I defined an enum named CodingKeys or whatever, they just don't work and 
    the testMessage and obj are still nil.
    But if I implement the init(from decoder: Decoder) construction and manually
    pass the coding keys which I defined to the decode function, all works fine.
    */
    public var testMessage: String? = nil
    public var obj: T? = nil
}

我将从响应中得到一个用户:

public class User: Codable
{
    private enum CodingKeys: String, CodingKey
    {
        case name
        case age
    }

    public var name: String? = nil
    public var age: Int32? = nil
}

这里是测试json:

var testJson = """
{
    "intA": 10,
    "intB": 20,
    "testMessage": "This is a test json",
    "obj":{
        "name": "LiHong",
        "age": 11
    }
}
"""

以下是我的做法运行:

do{
    var responseData = testJson.data(using: .utf8)
    var decoder = JSONDecoder()
    var response: ResponseWithObjectBean<User> = try decoder.decode(ResponseWithObjectBean<User>.self, from: responseData)
}catch let e{

}

我不知道如何在ResponseWithObjectBeanclass中定义CodingKeys,即使我做了,它也根本不起作用。但是如果我实现 init(from decoder: Decoder) throws 构造并手动传递我在 ResponseWithObjectBean 中定义的编码密钥,我可以获得所有属性。

这很简单,你只需要在子节点中手动编码和解码即可 class:

public class ResponseWithObjectBean<T: Codable> : ResponseBean {
    public var testMessage: String? = nil
    public var obj: T? = nil

    // Create another CodingKey compliant enum with another name for the new keys
    private enum CustomCodingKeys: String, CodingKey {
        case testMessage
        case obj
    }

    // Override the decoder
    required init(from decoder: Decoder) throws {
        try super.init(from: decoder)

        let container = try decoder.container(keyedBy: CustomCodingKeys.self)

        testMessage = try container.decode(String?.self, forKey: .testMessage)
        obj = try container.decode(T?.self, forKey: .obj)
    }

    // And the coder
    public override func encode(to encoder: Encoder) throws {
        try super.encode(to: encoder)

        var container = encoder.container(keyedBy: CustomCodingKeys.self)

        try container.encode(testMessage, forKey: .testMessage)
        try container.encode(obj, forKey: .obj)
    }

}

这样你就可以按照你想要的方式解码和编码了:

let decoder = JSONDecoder()
let response = try decoder.decode(ResponseWithObjectBean<User>.self, from: responseData)

let data = try JSONEncoder().encode(response)
print(String(data: data, encoding: .utf8))

编辑:为了防止您手动编写所有这些样板文件,您可以使用 Sourcery 等生成工具:https://github.com/krzysztofzablocki/Sourcery