14
votes

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

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: enter image description here 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;
    }
}
2
Is response.errorBody().toString(), a JSON? - Coder
No. At least I don't recognize it is: "okhttp3.ResponseBody$1@f0473b9" - gonczor
You are trying to construct errorResponse from GSON's fromJson which expects a JSON. Do you see where you are doing wrong? - Coder
Ah. That's what you mean. I see I've used toString() instead of string(). When I evaluate response.errorBody().string() I get {"error":{"message":"Not Found","error":{"status":404}}} which is what I want. I'll post your answer to mark problem as solved. Thanks :) - gonczor
Glad I could help!! - Coder

2 Answers

33
votes

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.

5
votes

you use string(), not toString()

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

to

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