如何使用codable递归编码我的自定义类(以及属性的其他自定义类)?

时间:2019-07-03 14:52:48

标签: swift serialization encode codable jsonencoder

class SocketMsgBody  {
    var body : AnyObject
}

public class SocketMsg : NSObject,Codable {

    var msgType : SocketMsgType
    var msgBody : SocketMsgBody

    enum CodingKeys: String, CodingKey {
        case msgType = "msgType"
        case msgBody = "msgBody"
    }

    enum NestedCodingKeys: String, CodingKey {
        case body
    }

    public init(with type:SocketMsgType) {
        msgType = type
        msgBody = SocketMsgBody(for: msgType)
    }
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(msgType, forKey: .msgType)

        var socketBodyInfo = container.nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .msgBody)
        try socketBodyInfo.encode(msgBody, forKey: .body)
    }
    public func serialize() throws -> String? {
        let encoder = JSONEncoder()
        guard let data = try? encoder.encode(self) else { return nil }
        let str = String(data: data, encoding: .utf8)
        return str
    }
}

我也想对msgbody进行编码,该怎么做?

0 个答案:

没有答案