将 JSON 映射到模型,而不考虑 Array 或 Object - ObjectMapper

Map JSON to the model irrespective of Array or Object - ObjectMapper

我在将 JSON 映射到我的对象 class 时遇到问题。这是我的模型对象

class CityObject : NSObject, Mappable{
var id : String?
var name : String?

required init?(map: Map) {
}

func mapping(map: Map) {
    id <- map["id"]
    name <- map["name"]
}
}

有时我从服务器得到的 JSON 响应可能是 Array 或像这样的对象。

数组:

{
"cities": [
{
  "id": "190",
  "name": "Elurupadu"
},
{
  "id": "1230",
  "name": "Sendhwa"
},
{
  "id": "1262",
  "name": "Multai"
},
{
  "id": "1480",
  "name": "Kherwara"
}]
}

有时候我会这样,

{
"cities": {"id": "6","name": "Hyderabad"}
}

它给了我 JSONObject.JSONArray 而不是 JSONArray。

我正在像这样映射到我的 class,

let list = Mapper<CityObject>().mapArray(JSONObject:cities["cities"])

这在我得到 JSONArray 时完美地工作,但是当我得到 JSONObject.

时同样不起作用

如何使用 ObjectMapper 处理两者?

根据 Paulw11 的建议,向下转换为 MAP 对我有用。

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
}