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;
}
}
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With