在Retrofit成功和错误回调中使用不同的模型进行反序列化

5

我正在使用的 API 在成功和失败时都会返回完全不同的响应。

成功:

{
   "token":"asdfasdfhkAADBSKJBJBJKBJBK^%&BJBLLKHKJBXZ",
   "email":"sample@sample.com",
   "role":"admin"
}

失败:

{
   "name": "NotAuthenticated",
   "message": "Invalid login.",
   "code": 401,
   "className": "not-authenticated"
}

我对Retrofit非常陌生,正在使用以下代码进行调用。

LoginRequest request = new LoginRequest(mobileNumber, password);
    ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

    Call<LoginResponse> call = apiService.authenticateUser(request);
    call.enqueue(new Callback<LoginResponse>() {
        @Override
        public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {


        }

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

        }
    });

可以看到,Retrofit 强制我在 successfailure 两种情况下都使用 ResponseObject。因此我无法将失败的响应转换为 POJO。

我已经尝试过自定义反序列化。但是为每个请求编写自定义反序列化器可能很快就会失控。

请帮忙解决问题。


1
你正在寻找 errorBody,我想。 - EpicPandaForce
我猜“失败”也会返回200 OK吧? - David Medenjak
不行,所有失敗響應都返回 400 到 499 之間的錯誤代碼。 - Giridhar Karnik
1
但是正如先前提到的,您的错误主体将在Response.errorBody中,不会干扰您的成功情况,使您能够拥有不同的数据类型。但是您仍然需要反序列化错误主体。 - David Medenjak
1个回答

0

我认为最好的解决方案是从Retrofit获取响应体并在GSON中自行序列化。我也在寻找其他解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接