改造成功和错误回调时使用不同的模型进行反序列化

Gri*_*mer 5 java android retrofit retrofit2

我正在使用的 API 对于成功和失败给出了完全不同的响应。

成功:

{
   "token":"asdfasdfhkAADBSKJBJBJKBJBK^%&BJBLLKHKJBXZ",
   "email":"sample@sample.com",
   "role":"admin"
}
Run Code Online (Sandbox Code Playgroud)

失败:

{
   "name": "NotAuthenticated",
   "message": "Invalid login.",
   "code": 401,
   "className": "not-authenticated"
}
Run Code Online (Sandbox Code Playgroud)

我对改造非常陌生,正在使用下面的代码进行调用。

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

        }
    });
Run Code Online (Sandbox Code Playgroud)

ResponseObject正如您所看到的,改造迫使我对success和都使用示例failure。因此我无法将失败响应转换为 pojo。

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

请帮忙。

小智 0

我认为最好的解决方案是对 Response Body 进行改造并在 GSON 中自行将其序列化。我也在寻找其他类型的解决方案。