How can I massage the 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/

+9
source share
5 answers

You need to change the declaration of the data into an array, as it is like in JSON:

 var data: [T]? 
+1
source

you need to use the mapArray method instead of map :

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

works for me

+1
source

I am doing 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 is that you need to check data and dataArray for null values.

+1
source

Anyone who uses SwiftyJSON, and if you want the object from JSON to not directly have a parent class, for example, you want to get "data" from it. You can do something like this,

 if let data = response.result.value { let json = JSON(data) let dataResponse = json["data"].object let responseObject = Mapper<DataClassName>().mapArray(JSONObject: dataResponse) } 

[DataClassName]? this return you [DataClassName]? as an answer.

0
source

Source: https://habr.com/ru/post/1261111/


All Articles