How can I do array mapping with objectmapper?

frontier picture frontier · Dec 11, 2016 · Viewed 9.4k times · Source

I have a response model that looks like this:

class ResponseModel: Mappable {

    var data: T?
    var code: Int = 0

    required init?(map: Map) {}

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

If the json-data is not an array it works:

{"code":0,"data":{"id":"2","name":"XXX"}}

but if it is an array, it does not work

{"code":0,"data":[{"id":"2","name":"XXX"},{"id":"3","name":"YYY"}]}

My mapping code;

let apiResponse = Mapper<ResponseModel>().map(JSONObject: response.result.value)

For details; I tried this code using this article : http://oramind.com/rest-client-in-swift-with-promises/

Answer

MohyG picture MohyG · Mar 13, 2017

you need to use mapArray method instead of map :

let apiResponse = Mapper<ResponseModel>().mapArray(JSONObject: response.result.value)