使用对象映射器映射响应

时间:2019-05-06 16:00:53

标签: ios swift

我正在使用https://github.com/tristanhimmelman/ObjectMapper来映射我对api调用的响应。我已经编写了通用方法来处理所有api调用。下面是方法

 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):
                if let status = response.status,  status.isSuccess {
                    if let data = response.data{
                        success(data)
                    }
                    else{
                       failure(kServerErrorData)
                    }
                }
                else{
                    if let  message = response.message {
                        failure(message)
                    }else {
                        failure(kServerError)
                    }
                }
            case .failure(let error):
                failure(error.localizedDescription)
            }
        }
    }

我的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) {}
}

现在通常我正在使用上述方法

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

当响应json有键时,这很好用,但是现在我必须处理在'data'中没有键的json

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

    "data": [
        {
            "user_info": {
                "name": "abx",
                "email": "abx@abx.com.pk",
                "phone": "4087082831"
            },
            "patient_info": {
                "p_name": "abx",
                "p_email": "abx@abx.com.pk",
                "p_phone": "4087082831"
            }
        },
        {

            "user_info": {
                "name": "abx",
                "email": "abx@abx.com.pk",
                "phone": "4087082831"
            },
            "patient_info": {
                "p_name": "abx",
                "p_email": "abx@abx.com.pk",
                "p_phone": "4087082831"
            }
        }
    ]
}

我在为上述json创建可映射类时遇到了麻烦,因为它在数据内部没有键。请帮忙!谢谢!

1 个答案:

答案 0 :(得分:0)

您可以尝试两种方法:

  1. <select class="full-width" id="RecipientInput" name="RecipientInput">
  2. 写另一个具有Api.shared.post(obj: [TokenResponse].self, endPoint: EndPoints.availability.rawValue, params: [Keys.token:BaseVC.authToken, Keys.availability:NSNumber(value: isAvailable)], success: successBlock)的{​​{1}}类