我尝试使用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对象/字典。我无法找到我出错的地方
答案 0 :(得分:1)
您的TimeEntryObject必须是Mappable。你输入了方法但没有在类声明中声明一致性。
class TimeEntryObject: Mappable
答案 1 :(得分:0)
我遇到了同样的问题,就我而言,我实现了Mappable协议。 Biut我还没有映射class的变量,这给了我一个空的json。
仅作为另一个选项/解决方案发布。可能会在需要时帮助某人。