Retrofit - Parsing generic api response with base

2019-06-24 12:15发布

问题:

I am using retrofit for rest api calls for my android app development. Since my all api response has "info"(Note that all api will have same key name) and "data" (Note that different apis have different key names) parameter, I have used a base class for the api responses. Below are the sample responses from API

Response 1

{
"info":{
        "statusCode":200,
        "message":"OK"
       },
"data":{
        "userId":2,
        "userName":"riyas"
       }
 }

Response 2

{
"info":{
        "statusCode":200,
        "message":"OK"
       },
"data":{
        "vegId":2,
        "vegName":"Potatoa"
       }
 }

I have created a base class named CloudBaseResponse and was able to get data in response.info . But I have no idea to parse the **data** . Please suggest me a way to handle using Retrofit

public class CloudBaseResponse {

   public BaseResponse response;

    public BaseResponse  getResponse() {
        return response;
    }

    public void setResponse(BaseResponse response) {
        this.response = response;
    }

    public class BaseResponse {
        public Info info;

    }

    public class Info{
        public String status;
        public String message;
    }

}

回答1:

You can use Generics to map your api response.

public class CloudBaseResponse<T> {
    @SerializedName("info")   
    private Info info;    

    @SerializedName("data")
    private T data;

    // Getters Setters..
}  

public class Info {
    private String status;
    private String message;

    // Getters Setters.. 
}

For example you have a Vegetable class.

public class Vegetable {
    private int vegetableId;
    private String vegetableName;

    // Getters Setters..
}

Later you can use with Retrofit like the following code:

Call<CloudBaseResponse<Vegetable>> getVegetables();


回答2:

Create a class named BaseModel and extends it in your response model (data)

public class BaseModel {
    Info info;

    public getInfo(){ return info;}
    public setInfo(Info info){ this.info = info; }

    public BaseModel() {
    }
}

public class Info{
    int statusCode;
    String message;

    public int getStatusCode() {
        return statusCode;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }
}

and your data class is like:

class Response extends BaseModel {
    public Data data;
}

class Data{
    public int vegId;
    public String vegName;
}

And finally, in Retrofit you have parse response to Response class