java - 安卓改造 : Can't convert the returned JSON reponse to the specified model class when response code ! = 200

标签 java android json retrofit retrofit2

JSON

当成功代码== 200

{
"data": {
    "user": {
        "id": 8,
        "name": "soleekuser",
        "email": "soleekuser@gmail.com",
        "job_title": "back end developer",
        "active": 1,
        "profile_pic": "http://52.174.22.188/soleekappapi/public/storage/profile_pics/Capture_1544361563.jpeg",
        "created_at": "2018-12-09 13:20:37"
    },
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjgsImlzcyI6Imh0dHA6Ly81Mi4xNzQuMjIuMTg4L3NvbGVla2FwcGFwaS9wdWJsaWMvYXBpL3VzZXJzL2xvZ2luIiwiaWF0IjoxNTQ0NjA1MDQ3LCJleHAiOjE1NDU4MTQ2NDcsIm5iZiI6MTU0NDYwNTA0NywianRpIjoiQk1sWTJ5NlVma043V0VhayJ9.npPbsHtV7G65jauwxltyvqS_xP7TmJetP9bTfTd9GB8"
},
"message": "Login Successfully",
"error": null
}

当我尝试使用错误的凭据(电子邮件或密码)进行身份验证时 响应代码 == 400(或任何其他非 200 代码)

{
"message": "invalid username or password",
"error": "invalid username or password"
}

模型类

public class Employee implements Serializable {

@SerializedName("data")
@Expose
private Data data;
@SerializedName("message")
@Expose
private String message;
@SerializedName("error")
@Expose
private String error;

public Employee() {
}

public Employee(Data data, String message, String error) {
    this.message = message;
    this.error = error;
    this.data = data;
}
// Getters & Setters
}

当缺少“数据”对象时,我应该怎么做才能将返回的 JSON 转换为模型类? (响应代码!= 200)

我认为即使缺少属性,Retrofit 也会自动将响应 json 转换为模型!

更重要的是

 call.enqueue(new Callback<Employee>() {
            @Override
            public void onResponse(Call<Employee> call, Response<Employee> response) {

                Log.e(TAG_FRAG_LOGIN, "Response code -> " + response.code() + " " + response.message() + " ");
                if (response.code() == 200) {
                    if (response.body() != null) {

                        // do stuff
// Everything works just fine when response code == 200, the body is not null.
                    }
                } else if (response.code() != 200){
                    Log.d(TAG_FRAG_LOGIN, "Response code ------> " + response.code() + " " + response.message() + " " + call.request().toString());
                    if (response.body() != null) {

                        // do stuff
// When response code != 200 the (response.body()) is always null

                    }
                }

为什么当响应码 != 200 时 respnse.body() 总是 null?

最佳答案

尝试制定处理错误消息的通用方法.. 像这样..

/**
 * this method used method response give error.
 *
 * @param context
 * @param response
 */
public static void getResponseErrorMessage(Context context, String str, Response response) {
    if (response.code() == 401 || response.code() == 400) {
        try {
            Gson gson = new Gson();
            CommonErrorModel errorModel = gson.fromJson(response.errorBody().string(), CommonErrorModel.class);
            showAlertDialog(context, str, errorModel.message == null ? context.getString(R.string.something_went_wrong) : errorModel.message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (response.code() == 500) {
        showAlertDialogMessage(context, str, context.getString(R.string.something_went_wrong));
    } else {
        showAlertDialogMessage(context, str, context.getString(R.string.something_went_wrong));
    }
}

此方法调用了 api response.. onResponse() 方法。

if (response != null && response.isSuccessful() && response.body() != null) {
  }
 else{
      getResponseErrorMessage(mContext, getString(R.string.app_name), response);
   }

也像这样制作错误消息 pojo 类..

public class CommonErrorModel {

@SerializedName("status")
public int status;

@SerializedName("message")
public String message;

关于java - 安卓改造 : Can't convert the returned JSON reponse to the specified model class when response code ! = 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53739703/

相关文章:

android - 如何仅打印 json 映射中值的特定部分?

java - 如何以良好的性能过滤 JSON 数据

javascript - 使用 AJAX/JSON 返回整个文件

java - fragment 启动时java.lang.NullPointerException的错误

android - 如何获取已安装应用程序的应用程序标签

java - Jackson 多态类型处理 - 属性被丢弃

java - 将 4 个 for 循环变成 1 个

java - "Constructor cannot be applied to given types"当构造函数有继承时

javascript - 使 href( anchor 标记)请求 POST 而不是 GET 作为传递参数

java - 从子类实例访问父类实例变量