简体   繁体   中英

Android Retrofit: Can't convert the returned JSON reponse to the specified model class when response code != 200

JSON

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
}

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"
}

Model Class

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
}

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

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

more importantly

 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

                    }
                }

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));
    }
}

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);
   }

also make error message pojo class like this..

public class CommonErrorModel {

@SerializedName("status")
public int status;

@SerializedName("message")
public String message;

}

When data object is missing from the response, it considered as different response than the the one used to create model. That's why it is null. You can pass blank data object from web service when there is no data. Meaning you will have the same response as when status is 200 but data object will have no data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM