Android Retrofit:当响应代码!= 200时,无法将返回的JSON响应转换为指定的模型类 [英] Android Retrofit: Can't convert the returned JSON reponse to the specified model class when response code != 200

查看:145
本文介绍了Android Retrofit:当响应代码!= 200时,无法将返回的JSON响应转换为指定的模型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JSON

成功代码== 200时

when success code == 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码)

When I try to authenticate with wrong credentials (email or password) Response code == 400 (or any other non 200 code)

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

What should I do to make it convert the return JSON to the model class when "data" object is missing? (Reponse code != 200)

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

I thought that Retrofit converts the response json to the model automatically even when there are missing attributes!

更重要的是

 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?

Why the respnse.body() is always null when response code != 200?

推荐答案

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

Try to make common method for handling error message.. like this way..

/**
 * 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响应.onResponse()方法.

this method called into api response.. onResponse() method.

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

也将错误消息设置为pojo类.

also make error message pojo class like this..

public class CommonErrorModel {

@SerializedName("status")
public int status;

@SerializedName("message")
public String message;

}

这篇关于Android Retrofit:当响应代码!= 200时,无法将返回的JSON响应转换为指定的模型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆