Getting json from retrofit's response errorBody

早过忘川 提交于 2020-08-01 06:28:11

问题


I am struggling with retrofit. When I post a request in my browser i get such a request:

And that's what I expect. However, when I try to parse this in my app I kept getting responses as in this thread. I've found tried to implement this solution, but my errorBody does not even resemble the answer from my browser: How can I get this JSON?

Just in case this is my response handler code:

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

And my ErrorResponse:

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

    public String getMessage() {
        return message;
    }

    public Error getError() {
        return error;
    }
}

回答1:


You are using toString() in GSON's fromJson which is not a JSON content. Replace your toString() as string() which will give you the JSON body. Also make sure to use the string() method only once and save the response in a variable, because it will return empty string if you used it again.



来源:https://stackoverflow.com/questions/42629992/getting-json-from-retrofits-response-errorbody

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!