首页 > 解决方案 > 在改造 2 中处理不同的响应

问题描述

我有一个返回两个不同响应的 Api。

成功时的响应是 -

{status="", message="", token="", subscription_active=""}

失败时的响应是 -

{
    "status": "failed",
    "message": "",
    "errors": []
}

这是我处理数据解析的方式 -

 Call<Object> call = jsonApi.hitOtp(otpPost);

       call.enqueue(new Callback<Object>() {
            @Override
            public void onResponse(Call<Object> call, Response<Object> response) {
                Log.d(TAG, "onResponse: "+response.body());

                if(response.body() instanceof OtpSuccessResponse){
                     Toast.makeText(OtpActivity.this, otpSuccRes.getMessage(), Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(OtpActivity.this,"Failed", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Object> call, Throwable t) {
                Log.d(TAG, "onFailure: "+t.getMessage());
            }
        });

我在日志中得到了成功响应,但 if 条件不起作用。相反,我得到 -

 java.lang.ClassCastException 


com.google.gson.internal.LinkedTreeMap cannot be cast to 
com.avaskm.yellowalleyproject.Retrofit.Otp.OtpSuccessResponse

我的 OnSuccess pojo 课程 -

public class OtpSuccessResponse {


   @SerializedName("status")
   @Expose
   private String status;
   @SerializedName("message")
   @Expose
   private String message;
   @SerializedName("token")
   @Expose
   private String token;

   @SerializedName("subscription_active")
   @Expose
   private String subscriptionActive;

   public OtpSuccessResponse(String status, String message, String token, String subscriptionActive) {

      this.status = status;

      this.message = message;

      this.token = token;

      this.subscriptionActive = subscriptionActive;
   }


}

标签: androidandroid-studioretrofit2

解决方案


推荐阅读