Mina Fared Mina Fared - 3 months ago 8
JSON Question

how to parse error json returned by a 422 response?

this is the response when using fiddler

HTTP/1.1 422 Unprocessable Entity
Server: nginx/1.9.4
Date: Thu, 25 Feb 2016 18:03:15 GMT
Content-Type: application/json
Content-Length: 31
Connection: close
Status: 422 Unprocessable Entity
X-Content-Type-Options: nosniff

{"error":"username is invalid"}


this is my code to call web service and i used retrofit web service I can parse data when success(code 201) but when code (422) I could not find error message

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

if (response.isSuccess()) {
txt_pressure.setText("username: " + response.body().username);
} else {
// how to parse error when 422
}

@Override
public void onFailure(Call<UserRegister> call, Throwable t) {
Toast.makeText(MainActivity.this, "Network error has occurred. Retry again...",
Toast.LENGTH_SHORT).show();
}
});

Answer

Try this

if(response.code() == 422) {
    //do whatever you want
}