Reputation: 7295
I am having trouble in mapping the JSON to my object class. Here is my Model Object
class CityObject : NSObject, Mappable{
var id : String?
var name : String?
required init?(map: Map) {
}
func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
}
}
The JSON response I get from server sometime may be Array or an Object like this.
Array:
{
"cities": [
{
"id": "190",
"name": "Elurupadu"
},
{
"id": "1230",
"name": "Sendhwa"
},
{
"id": "1262",
"name": "Multai"
},
{
"id": "1480",
"name": "Kherwara"
}]
}
Sometimes I get like this,
{
"cities": {"id": "6","name": "Hyderabad"}
}
Instead of an JSONArray it gives me JSONObject.
I am mapping to my class like this,
let list = Mapper<CityObject>().mapArray(JSONObject:cities["cities"])
This works perfectly when I get JSONArray, but the same doesn't work when I get JSONObject.
How to handle both with ObjectMapper?
Upvotes: 2
Views: 826
Reputation: 7295
As per Paulw11 suggestion down casting to MAP worked for me.
if let list = Mapper<CityObject>().mapArray(JSONObject:cities["cities"]){
//Handles JSONArray response
}
else if let list = Mapper<CityObject>().map(JSONObject: cities["cities"]){
//Handles JSONObject response
}
else{
//Handles error
}
Upvotes: 2