我正在尝试使用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对象/字典。我找不到哪里出了问题

最佳答案

您的TimeEntryObject必须是可映射的。您放入了方法,但没有在类声明中声明一致性。

class TimeEntryObject: Mappable

07-26 09:38