【问题标题】:Parse REST response message using retrofit and observable使用改造和可观察解析 REST 响应消息
【发布时间】:2019-03-15 16:31:20
【问题描述】:

当我使用错误的登录信息(使用邮递员)时,我的 API 会返回此信息:

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

我正在使用这种方法来获取响应消息:

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

并且输出(快餐栏显示的内容)与邮递员返回的相同。

handleresponse 参数retrofit2.Response&lt;Response&gt; responseretrofit2 Response 和我自己的&lt;Response&gt; 类组成,如下所示:

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

    public String getMessage() {
        return message;
    }
}

我怎样才能让message 只显示在snackbar 中?

我尝试了以下代码,但只得到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();
}

【问题讨论】:

    标签: java json rest observable retrofit2


    【解决方案1】:

    根据您的 json,响应错误正文是一个具有字段 error 的对象,其中包含字段 message。这意味着您首先需要获取错误对象,然后是消息:

    JSONObject jObjError = new JSONObject(response.errorBody().string()).getJSONObject("error");
    Toast.makeText(getContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
    

    【讨论】:

    • 好的,这行得通。可以肯定的是,这是一个很好的方法吗?我见过很多其他方法,但没有一个对我有用,但我想这取决于我得到的 json,对吧?
    • 说实话,我觉得这种方式有点手动,因此容易出错。由于您使用的是gson,因此您也可以随时让它为您反序列化错误主体。但最后,我不会说这是错误的。这只是另一种做事方式。
    • 因为我为我的 api 使用 Loopback 框架,但我无法获取消息...非常复杂的框架..
    猜你喜欢
    • 2019-08-10
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 2019-03-27
    相关资源
    最近更新 更多