gpt4 book ai didi

swift - ObjectMapper 不序列化新字段

转载 作者:行者123 更新时间:2023-11-28 16:06:50 24 4
gpt4 key购买 nike

我有一个类:

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 数据库已经存储了 ChatMessage 对象时,我稍后将 created 字段添加到映射中。

现在,当我实例化 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字段怎么没有出现在字符串中?

最佳答案

问题出在 Int64 类型的映射中,如 issue 中所述在 github 上。

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

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

关于swift - ObjectMapper 不序列化新字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40175068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com