【问题标题】:Getting json from retrofit's response errorBody从改造的响应errorBody中获取json
【发布时间】:2017-07-26 13:56:07
【问题描述】:

我正在为改造而苦苦挣扎。当我在浏览器中发布请求时,我收到了这样的请求:

这就是我所期望的。但是,当我尝试在我的应用程序中解析它时,我不断收到回复,就像在this 线程中一样。我发现尝试实施this 解决方案,但我的errorBody 甚至与我浏览器中的答案都不相似: 我怎样才能得到这个 JSON?

以防万一这是我的响应处理程序代码:

void handleResponse(Response response){
    TextView textView = (TextView)findViewById(R.id.empty_list_tv);
    if(response.isSuccessful())
        textView.setText(response.toString());
    else {
        Gson gson = new Gson();
        ErrorResponse errorResponse = gson.fromJson(
                response.errorBody().toString(),
                ErrorResponse.class);
        textView.setText(response.errorBody().toString());
    }
}

还有我的ErrorResponse:

public class ErrorResponse {
    @SerializedName("message")
    private String message;
    @SerializedName("error")
    private Error error;

    public String getMessage() {
        return message;
    }

    public Error getError() {
        return error;
    }
}

【问题讨论】:

  • response.errorBody().toString(), 是 JSON 吗?
  • 没有。至少我不认识它是:“okhttp3.ResponseBody$1@f0473b9”
  • 您正在尝试从 GSON 的 fromJson 构造 errorResponse,它需要 JSON。你知道你哪里做错了吗?
  • 啊。这就是你的意思。我看到我使用了toString() 而不是string()。当我评估response.errorBody().string() 我得到{"error":{"message":"Not Found","error":{"status":404}}} 这就是我想要的。我将发布您的答案以将问题标记为已解决。谢谢:)
  • 很高兴能帮上忙!!

标签: android json retrofit2 gson


【解决方案1】:

您在 GSON 的 fromJson 中使用 toString(),这不是 JSON 内容。将您的 toString() 替换为 string(),这将为您提供 JSON 正文。 还要确保只使用一次string() 方法并将响应保存在变量中,因为如果再次使用它将返回空字符串。

【讨论】:

  • 这行得通,但如果我第二次调用string() 方法,它将返回空字符串
  • @KhalidTaha 当您说您第二次调用该方法时,您究竟是什么意思?你能详细说明一下吗
  • 我的意思是如果你第一次调用string()方法,它会返回正确的字符串,但是如果你再调用一次,它会返回空字符串。
  • 想详细说明或更新我的答案并提供有效解释?它可能会帮助其他人寻找答案@KhalidTaha
  • 感谢您的回答。使用 string() 有效,但我不得不将其包围在 try catch 中。
【解决方案2】:

你使用 string(),而不是 toString()

 ErrorResponse errorResponse = gson.fromJson(
                response.errorBody().toString(),
                ErrorResponse.class);

到

ErrorResponse errorResponse = gson.fromJson(
                response.errorBody().string(),
                ErrorResponse.class);

【讨论】:

    猜你喜欢
    • 2016-03-23
    • 2017-04-19
    • 2017-04-22
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多