我有一个班级:
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
字段怎么没有出现在字符串中?
答案 0 :(得分:1)
问题出在github上issue中提到的Int64
类型的映射。
通过将created
的映射更改为以下形式,一切正常:
created <- (map["created"], TransformOf<Int64, NSNumber>(fromJSON: { $0?.int64Value }, toJSON: { $0.map { NSNumber(value: $0) } }))