Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 398
frontier Avatar asked Dec 11 '16 18:12

frontier


2 Answers

you need to use mapArray method instead of map :

let apiResponse = Mapper<ResponseModel>().mapArray(JSONObject: response.result.value)
like image 75
MohyG Avatar answered Oct 12 '22 13:10

MohyG


What I do is something like this:

func mapping(map: Map) {
    if let _ = try? map.value("data") as [Data] {
       dataArray <- map["data"]
    } else {
       data <- map["data"]
    }

    code <- map["code"]
}

where:

var data: T?
var dataArray: [T]?
var code: Int = 0

The problem with this is that you need to check both data and dataArray for nil values.

like image 38
Abrahanfer Avatar answered Oct 12 '22 12:10

Abrahanfer