Parse REST response message using retrofit and observable

问题: My API returns this when I use wrong login information (using postman): { "error": { "statusCode": 401, "name": "Error", "message": "login fai...

问题:

My API returns this when I use wrong login information (using postman):

{
    "error": {
        "statusCode": 401,
        "name": "Error",
        "message": "login failed",
        "code": "LOGIN_FAILED",
        "stack": "Error: login failedn    at ...path..."
    }
}

I am using this method to get the response message:

private void handleResponse(retrofit2.Response<Response> response) {

            if (response.isSuccessful()) {
                emailField.setText(null);
                passwordField.setText(null);

                Intent intent = new Intent(getActivity(), MainActivity.class);
                startActivity(intent);
            } else {
                try {
                    showSnackBarMessage(response.errorBody().string());
                } catch (Exception e) {
                    showSnackBarMessage(e.getMessage());
                }
            }
}

And the output (what snackbar shows) is the same as postman returns.

handleresponse parameter retrofit2.Response<Response> response consists of retrofit2 Response, and my own <Response> class which looks like this:

public class Response {
    @SerializedName("message")
    @Expose
    private String message;

    public String getMessage() {
        return message;
    }
}

How can I get only message to show in snackbar?

I have tried the following code, but I get only No value for message.

try {
     JSONObject jObjError = new JSONObject(response.errorBody().string());
     Toast.makeText(getContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
     Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}

回答1:

According to your json the response error body is an object with a field error which contains a field message. This means you first need to get the error object and then the message:

JSONObject jObjError = new JSONObject(response.errorBody().string()).getJSONObject("error");
Toast.makeText(getContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
  • 发表于 2019-03-17 19:34
  • 阅读 ( 202 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除