iOS - Map a root JSON array with ObjectMapper in swift

Nicolas HENAUX picture Nicolas HENAUX · Sep 2, 2015 · Viewed 27.2k times · Source

I use the library ObjectMapper to map json with my objects but I have some issues to map a root json Array.

This is the received json :

[
   {
       CustomerId = "A000015",
       ...
   },
   {
       CustomerId = "A000016",
       ...
   },
   {
       CustomerId = "A000017",
       ...
   }
]

This is my object

class Customer : Mappable
{
    var CustomerId : String? = nil

    class func newInstance(map: Map) -> Mappable? {
        return Customer()
    }

    func mapping(map: Map) {
        CustomerId   <- map["CustomerId"]
    }
}

I map the json in my controller with

let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as! NSArray

if (error != nil) {
    return completionHandler(nil, error)
} else {
    var customers = Mapper<Customer>().map(json)
}

But it doesn't work, I tried Mapper<[Customer]>().map(json) but it doesn't work too. Finally I tried to create a new swift object CustomerList containing a Customer array but it doesn't work.

Do you have an idea of how to map json of a root array ?

Thanks.

Answer

Nicolas HENAUX picture Nicolas HENAUX · Sep 2, 2015

I finally solve my problem :

The mapping method in the controller should be

let json : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error)

if (error != nil) {
    return completionHandler(nil, error)
} else {
    var customer = Mapper<Customer>().mapArray(json)! //Swift 2
    var customer = Mapper<Customer>().mapArray(JSONArray: json)! //Swift 3
}

If it can help someone.