Search code examples
iosjsonswift3objectmapper

ObjectMapper toJson empty


I'm trying to deserialize an object into a JSON dictionary with ObjectMapper but the deserializing functions always return empty objects.

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"]
}
}

Here's the part where I fill my TimeEntryContainer object

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) ")

Even though the values of my timeEntry object are correctly set, the functions Mapper().toJSONString(), Mapper().toJSON() and even timeEntry.toJSON() and timeEntry.toJSONString() return an empty JSON object / dictionary. I can't find where I went wrong


Solution

  • Your TimeEntryObject must be Mappable. You put in the methods but you didn't declare conformance in the class declaration.

    class TimeEntryObject: Mappable