Nicolas HENAUX Nicolas HENAUX - 4 months ago 104
Swift Question

iOS - Map a root JSON array with ObjectMapper in swift

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

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 : Array<Customer> = Mapper<Customer>().mapArray(json)!
}

If it can help someone.

Comments