从改造的响应错误中获取jsonBody

gon*_*zor 9 android json gson retrofit2

我正在努力改造.当我在浏览器中发布请求时,我收到了这样的请求:在此输入图像描述

这就是我的期望.但是,当我尝试在我的应用程序中解析它时,我一直得到响应,就像在这个帖子中一样.我发现尝试实现这个解决方案,但我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());
    }
}
Run Code Online (Sandbox Code Playgroud)

我的ErrorResponse:

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

    public String getMessage() {
        return message;
    }

    public Error getError() {
        return error;
    }
}
Run Code Online (Sandbox Code Playgroud)

Cod*_*der 19

您正在使用toString()GSON的fromJson,它不是JSON内容.更换你toString()string(),这将给你的身体JSON.另外,请确保string()仅使用该方法一次并将响应保存在变量中,因为如果再次使用它,它将返回空字符串.

  • 用有效的解释来详细说明或更新我的答案吗?它可能会帮助其他人寻找答案@KhalidTaha (2认同)

Ras*_*iri 9

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

 ErrorResponse errorResponse = gson.fromJson(
                response.errorBody().toString(),
                ErrorResponse.class);
Run Code Online (Sandbox Code Playgroud)

ErrorResponse errorResponse = gson.fromJson(
                response.errorBody().string(),
                ErrorResponse.class);
Run Code Online (Sandbox Code Playgroud)