Search code examples
swiftobjectmapper

How can I do array mapping with objectmapper?


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/


Solution

  • You need to change your declaration of data to an array, since that's how it is in the JSON:

    var data: [T]?