SwiftyJD SwiftyJD - 4 months ago 103
Swift Question

How to map a JSON dictionary in ObjectMapper?

I have json data that looks like this:

{
"balance": {
"pointsEarned": 3,
"pointsAvailable": 3,
"pointsOnHold": 0,
"pointsConsumed": 0,
"nextReward": 6
}
}


I'm trying to map the "balance" so I can get the other values:

class AccountBalance: Mappable {

var balance: Dictionary<String, AnyObject>?
var pointsAvailable: Int?

required init?(_ map: Map) {

}

func mapping(map: Map) {

balance <- map["balance.value"]
pointsAvailable <- map ["pointsAvailable"]
}
}


According to the objectMapper github page its done this way:

ObjectMapper supports dot notation within keys for easy mapping of nested objects. Given the following JSON String:

"distance" : {
"text" : "102 ft",
"value" : 31
}


You can access the nested objects as follows:

func mapping(map: Map) {
distance <- map["distance.value"]
}


Whenever I try and access the "balance" I get a nil. Any idea what I may be doing wrong?

Answer

Note in the example you linked to, distance has a value property, which can be accessed with map["distance.value"]:

"distance" : {
     "text" : "102 ft",
     "value" : 31
}

In your example, balance has no sub-field calledvalue, and so map["balance.value"] will fail.

Use map["balance"] to map the balance variable to the dictionary:

class AccountBalance: Mappable {

    var balance: Dictionary<String, AnyObject>?
    var pointsAvailable: Int?

    required init?(_ map: Map) {
    }

    func mapping(map: Map) {

        balance <- map["balance"]
        pointsAvailable <- map ["pointsAvailable"]
    }
}
Comments