iOS - Map a root JSON array with ObjectMapper in swift
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.
Using JSONObjectWithData(::)
with the correct conditional downcasting type
Your JSON is of type [[String: AnyObject]]
. Therefore, with Swift 2, you can use JSONObjectWithData(::)
with a conditional downcasting of type [[String: AnyObject]]
in order to prevent using NSArray
or AnyObject!
:
do { if let jsonArray = try NSJSONSerialization .JSONObjectWithData(data, options: []) as? [[String: AnyObject]] { /* perform your ObjectMapper's mapping operation here */ } else { /* ... */ }}catch let error as NSError { print(error)}
Mapping to Customer
using mapArray(:)
method
The ObjectMapper
's Mapper
class provides a method called mapArray(:)
that has the following declaration:
public func mapArray(JSONArray: [[String : AnyObject]]) -> [N]?
The ObjectMapper
documentation states about it:
Maps an array of JSON dictionary to an array of Mappable objects
Thus, your final code should look something like this:
do { if let jsonArray = try NSJSONSerialization .JSONObjectWithData(data, options: []) as? [[String: AnyObject]] { let customerArray = Mapper<Customer>().mapArray(jsonArray) print(customerArray) // customerArray is of type [Customer]? } else { /* ... */ }}catch let error as NSError { print(error)}
Mapping to Customer
using map(:)
method
The ObjectMapper
's Mapper
class provides a method called map(:)
that has the following declaration:
func map(JSONDictionary: [String : AnyObject]) -> N?
The ObjectMapper
documentation states about it:
Maps a JSON dictionary to an object that conforms to Mappable
As an alternative to the previous code, the following code shows how to map your JSON to Customer
using map(:)
:
do { if let jsonArray = try NSJSONSerialization .JSONObjectWithData(data, options: []) as? [[String: AnyObject]] { for element in jsonArray { let customer = Mapper<Customer>().map(element) print(customer) // customer is of type Customer? } } else { /* ... */ }}catch let error as NSError { print(error)}
The easiest solution is provided by AlamofireObjectMapper. Use the responseArray()
convenience method:
Alamofire.request(endpoint).responseArray { (response: DataResponse<[MyMappableClass]>) in if let result = response.result.value { // Customer array is here } else if let error = response.result.error { // Handle error } else { // Handle some other not networking error } }