使用JSONEncoder编码子类

时间:2018-06-05 19:36:15

标签: json swift inheritance encoding

我现在坐在这里,正如我初想的那样,非常简单的问题。我想在Swift中编码一个对象,继承另一个Class

这里的课程:

class NetworkMessage: Codable {
    var version:Int?
}

class AddPlayerRequest: NetworkMessage {

    var playerName: String?
    var playerHashedPw: String?

    private enum CodingKeys: String, CodingKey {
        case playerName
        case playerHashedPw
    }

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

        try super.encode(to: encoder)
    }

}

我知道有数以百万计的例子,我会说我确信我做了类似示例中的所有事情,但似乎我错过了一些东西,因为当我尝试编码AddPlayerRequest时这样:

let apr = AddPlayerRequest()
apr.playerName = "Test"
apr.playerHashedPw = "hynt87t7t76yt=="
apr.version = 1

do {
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    let data = try encoder.encode(apr)
    let jsonStr = String(data: data, encoding: .utf8)
} catch {
    print(error)
}

输出结果为:

  

{

     

}

编辑:似乎相同的代码正在处理另一个MAC。任何人都知道为什么Code可以在一个MAC上运行,而不是在另一个MAC上运行?

0 个答案:

没有答案
相关问题