我们如何使用Retrofit 2处理不同的响应类型?

时间:2016-02-23 16:47:19

标签: android retrofit2

我有一个webservice,它返回一系列序列化的MyPOJO对象:

[
  { //JSON MyPOJO },
  { //JSON MyPOJO }
]

是错误对象:

{  
  'error': 'foo', 
  'message':'bar' 
}

使用retrofit2,我该如何检索错误?

Call<List<MyPOJO>> request = ...
request.enqueue(new Callback<List<MyPOJO>>() {
  @Override
  public void onResponse(Response<List<MyPOJO>> response) {
      if (response.isSuccess()) {
          List<MyPOJO> myList = response.body();
          // do something with the list...
      } else {
          // server responded with an error, here is how we are supposed to retrieve it
          ErrorResponse error = ErrorResponse.fromResponseBody(apiService.getRetrofitInstance(), response.errorBody());
          processError(error);
          // but we never get there because GSON deserialization throws an error !
      }
  }

  @Override
  public void onFailure(Throwable t) {
    if(t instanceof IOException){
        // network error 
    }else if(t instanceof IllegalStateException){
        // on server sending an error object we get there
        // how can I retrieve the error object ?
    }else { 
        // default error handling 
    }       
  }
}

以下是GSON例外:

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

使用GsonConverterFactory

创建改造实例

2 个答案:

答案 0 :(得分:18)

我有一个类似的问题,我通过使用通用Object解决了它,然后使用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
    }
});

在我的情况下,我有MyPOJO或MyError返回,我可以肯定它会是其中之一。

在其他情况下,无论请求是否成功,我都让后端返回相同的响应对象 然后在这个响应对象中,我在“对象”字段中得到了我的实际数据。然后我可以使用实例来确定我拥有的数据类型。在这种情况下,无论调用是什么,我总是返回相同的对象。

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;
}

答案 1 :(得分:10)

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) {

        }
    });
}