Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a JSON dictionary in ObjectMapper?

Tags:

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?

like image 386
SwiftyJD Avatar asked Jul 12 '16 22:07

SwiftyJD


1 Answers

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"]
    }
}
like image 145
Luke Van In Avatar answered Nov 15 '22 06:11

Luke Van In