How can we handle different response type with Retrofit 2?

回眸只為那壹抹淺笑 提交于 2019-11-28 05:52:50

I had a similar issue and I solved it by using a generic Object and then testing what type of response I had using instanceof

Call<Object> call = api.login(username, password);
call.enqueue(new Callback<Object>() 
{
    @Override
    public void onResponse(Response<Object> response, Retrofit retrofit)
    {
         if (response.body() instanceof MyPOJO )
         {
            MyPOJO myObj = (MyPOJO) response.body();
            //handle MyPOJO 
         }
         else  //must be error object
         {
            MyError myError = (MyError) response.body();
            //handle error object
         }
    }

    @Override
    public void onFailure(Throwable t) 
    {
     ///Handle failure
    }
});

In my case I had either MyPOJO or MyError returned and I could be sure it would be one of these.

In other cases then I had the backend return the same Response Object no matter if the request was successful or not.
Then inside this response object I had my actual data within an "Object" field. Then I can use instance of to determine what type of data I had. In this case I always had the same object being returned, no matter what the call was.

public class MyResponse {

    private int responseCode;
    private String command;
    private int errorno;
    private String errorMessage;
    private Object responseObject;   //This object varies depending on what command was called
    private Date responseTime;
}
Call<LoginResponse> call = apiService.getUserLogin(usernametext, passwordtext);
    call.enqueue(new Callback<LoginResponse>() {
        @Override
        public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
            Log.e("responsedata","dd"+response.toString());
            if (response.code()==200) {
                showMessage(response.body().getMessage());
                Intent intent = new Intent(LoginActivity.this, MainAct.class);
                startActivity(intent);
            }
            else
                try {
                    LoginError loginError= gson.fromJson(response.errorBody().string(),LoginError.class);
                    showMessage(loginError.getMessage());
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        @Override
        public void onFailure(Call<LoginResponse> call, Throwable t) {

        }
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!