我试图用ObjectMapper将对象反序列化为JSON字典,但是反序列化函数总是返回空对象。
class TimeEntryContainer: Mappable {
//MARK: Properties
var entry: TimeEntryObject = TimeEntryObject()
//MARK: Initializers
init() {}
init(_ issue: Issue, hours: Double, activityId: Int) {
self.entry = TimeEntryObject(issue, hours: hours, activityId: activityId)
}
required init?(map: Map) {
mapping(map: map)
}
//MARK: Private Methods
func mapping(map: Map) {
entry <- map["time_entry"]
}
}
class TimeEntryObject {
//MARK: Properties
var issueId = -1
var projectId = ""
var hours = Double()
var activityId = -1
var comments = ""
//MARK: Initializers
init() {}
init(_ issue: Issue, hours: Double, activityId: Int) {
self.issueId = issue.id
self.projectId = issue.project
self.hours = hours
self.activityId = activityId
}
required init?(map: Map) {
mapping(map: map)
}
//MARK: Private functions
func mapping(map: Map) {
issueId <- map["issue_id"]
projectId <- map["project_id"]
hours <- map["hours"]
activityId <- map["activity_id"]
comments <- map["comments"]
}
}下面是我填充TimeEntryContainer对象的部分
let timeEntry = TimeEntryContainer()
timeEntry.entry.projectId = (issue?.project)!
timeEntry.entry.activityId = activityId
timeEntry.entry.hours = timeEntered
timeEntry.entry.comments = commentEdit.text ?? ""
let deserialized = Mapper().toJSONString(timeEntry)
print("hours: \(deserialized) ")即使正确设置了我的timeEntry对象的值,函数Mapper().toJSONString()、Mapper().toJSON()甚至timeEntry.toJSON()和timeEntry.toJSONString()都返回一个空的JSON对象/字典。我找不到哪里出错了
发布于 2017-04-29 00:12:06
您的TimeEntryObject必须是可映射的。您输入了方法,但没有在类声明中声明一致性。
class TimeEntryObject: Mappable 发布于 2019-11-19 12:03:50
我也有同样的问题,在我的例子中,我已经实现了Mappable协议。我没有映射出类的变量,这给了我空的json。
张贴只是另一种选择/解决方案。可能会在需要的情况下帮助别人。
https://stackoverflow.com/questions/43688959
复制相似问题