Objectmapper: Can't map array with generic method

Created on 6 May 2019  路  5Comments  路  Source: tristanhimmelman/ObjectMapper

i want to map my response for api calls. I have written a generic method to handle all api call. Below is method

 func post<T: Mappable>(obj: T.Type, endPoint:String ,params:[String:Any], success : @escaping (T) -> Void, failure : @escaping (String) -> Void){
        Alamofire.request(baseUrl+endPoint,method: .post, parameters:params).responseObject { (response:DataResponse<BaseResponse<T>>) in
            switch response.result {
            case .success(let response):
            .....
            case .failure(let error):
            .....
            }
        }
    }

BaseResponse:

struct BaseResponse<T:Mappable>:Mappable{
    var status:Int?
    var message:String?
    var data:T?
    mutating func mapping(map: Map) {
        status  <- map["status"]
        message <- map["message"]
        data    <- map["data"]
    }
    init?(map: Map) {}
}

Now usually i am using above method like this

 Api.shared.post(obj: TokenResponse.self, endPoint: EndPoints.availability.rawValue, params: [Keys.token:BaseVC.authToken, Keys.availability:NSNumber(value: isAvailable)], success: successBlock)

This works fine when response json have keys but now i have to handle this json which dont have keys inside 'data'

This is json i wanna parse:

{
    "status": 200,
    "message": "Patient List",

    "data": [
        {
            "user_info": {
                "name": "abx",
                "email": "[email protected]",
                "phone": "4087082831"
            },
            "patient_info": {
                "p_name": "abx",
                "p_email": "[email protected]",
                "p_phone": "4087082831"
            }
        },
        {

            "user_info": {
                "name": "abx",
                "email": "[email protected]",
                "phone": "4087082831"
            },
            "patient_info": {
                "p_name": "abx",
                "p_email": "[email protected]",
                "p_phone": "4087082831"
            }
        }
    ]
}

I'm having trouble creating mappable class for above json since it don't have keys inside data. Please help! thanks!

All 5 comments

Hello @asadhyt
Probably you should declare var data as [T]?.

I think this issue is duplicated with #1043

@PH9 - I'm pretty sure this issue is separate since it both doesn't involve Swift 5 and because I am still experiencing it after upgrading to ObjectMapper 3.5.x.

This issue as I understand it here is that ObjectMapper understands a slew of types that don't conform to the Mappable protocol - both "Nesting" objects like arrays and dictionaries and "Primative" values like strings and booleans. However, because they don't conform to the Mappable protocol, @asadhyt can't pass them as the generic argument to his class and, even if he could, the Mapper generic format doesn't successfully unwrap objects that aren't Mappable. I haven't dug into the code yet, but I think the solution is either going to be to make those types all Mappable or to correct the Mapper so that it can understand either Mappable types or these raw mappable types.

For now, @asadhyt, I'm working around this in my app in the following way:

  1. My BaseResponse class is now just a protocol that defines an expectation of the fields a response will have. In your case, status, message, and data.
  2. I made a ResponseWithObject<T: Mappable> and ResponseWithArrayOfObject<T: Mappable> class, each of which looks like your class and conform to BaseResponse, except the Array variant follows @RomanPodymov's suggestion of declaring data to be of type [T]?
  3. I added a second generic to my post method of Response: BaseResponse that declares which response type is expected.

Thanks everyone.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

loryhuz picture loryhuz  路  4Comments

YunyueLin picture YunyueLin  路  3Comments

amg1976 picture amg1976  路  3Comments

pcompassion picture pcompassion  路  3Comments

mirzadelic picture mirzadelic  路  4Comments