ObjectMapper没有序列化新字段

时间:2016-10-21 11:07:28

标签: swift swift3 realm objectmapper

我有一个班级:

class ChatMessage: Object, Mappable {
    dynamic var fromId = ""
    dynamic var toId = ""
    dynamic var message = ""
    dynamic var fromName = ""
    dynamic var created: Int64 = 0



    required convenience init?(map: Map) {
        self.init()
    }

    func configure(_ fromId:String,toId:String, message:String) {
        self.fromId=fromId
        self.toId=toId
        self.message=message
        self.created = Int64((NSDate().timeIntervalSince1970 * 1000.0))

    }

    func mapping(map: Map) {
        created  <- map["created"] //a: this was added later
        fromId <- map["fromId"]
        toId <- map["toId"]
        message <- map["message"]
        fromName  <- map["fromName"]

    }
}

我正在使用ObjectMapper将对象序列化为JSON,并使用Realm将其存储在本地数据库中。 当Realm db已经存储created对象时,我稍后将ChatMessage字段添加到映射中。

现在,当我实例化ChatMessage对象并尝试使用ObjectMapper将其转换为JSON对象时。以下是代码:

  func sendChatMessage(_ chatMessage:ChatMessage, callback: @escaping DataSentCallback) -> Void {
        var chatMessageString:String!

        let realm = DBManager.sharedInstance.myDB

        try! realm?.write {
            chatMessageString = Mapper().toJSONString(chatMessage, prettyPrint: false)!

        }
...
}

现在当我打印chatMessage时,我得到了:

ChatMessage {
    fromId = 14;
    toId = 20;
    message = 2;
    fromName = ;
    created = 1477047392597;
}

当我打印chatMessageString时,我得到:

"{\"toId\":\"20\",\"message\":\"2\",\"fromName\":\"\",\"fromId\":\"14\"}"

created字段怎么没有出现在字符串中?

1 个答案:

答案 0 :(得分:1)

问题出在github上issue中提到的Int64类型的映射。

通过将created的映射更改为以下形式,一切正常:

created  <- (map["created"], TransformOf<Int64, NSNumber>(fromJSON: { $0?.int64Value }, toJSON: { $0.map { NSNumber(value: $0) } }))