In retrofit to map json response to pojo usually we do this
@POST
Call getDataFromServer(@Url String url, @Body HashMap ha
Android:dynamically pass model class to retrofit callback
There is 2 ways you can do this .........
1. Generics
2. Combine all POJO into one ......
Generics
In the Generics you have to pass the method with the class. pleas have look on example .....
ApiCalls api = retrofit.create(ApiCalls.class);
Call call = api.getDataFromServer(StringConstants.URL,hashMap);
callRetrofit(call,1);
public static void callRetrofit(Call call,final int i) {
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if(i==1){
User user = (User) response.body(); // use the user object for the other fields
}else if (i==2){
Patient user = (Patient) response.body();
}
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
}
NOTE:- Above retrofit call TypeCast your response into YOUR OBJECT
, so you can access its field and methods
Combine all POJO into one
It is very easy to use . You have to combine your all POJO class into one and use them inside the Retrofit. please have look on below example ....
I have two API login and user......
In Login API i have get JSON response like this ...
{ "success": True, "message": "Authentication successful"}
above JSON , POJO look like this
public class LoginResult{
private String message;
private boolean success;
//constructor , getter and setter
}
and Retrofit call look like this .....
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
In User API i have get JSON response like this ...
{"name": "sushildlh", "place": "hyderabad"}
above JSON , POJO look like this
public class UserResult{
private String name;
private String place;
//constructor , getter and setter
}
and Retrofit call look like this .....
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
Just combine both of above JSON response into one .....
public class Result{
private String name;
private String place;
private String message;
private boolean success;
//constructor , getter and setter
}
and use Result inside Your API call ......
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
Note:- You directly combine your 2 POJO class and accessing it. (This is very complicate if you have response very large and provide duplication if some KEY is same with different Variable type )