Retrofit response.errorBody cannot be converted to JsonObject or Java Obejct

1k views Asked by At

When the API is called it return an object in onScuccess with status code 201 and when not in onSuccess along with status code 422 it also gives an object like this

{
    "errors": [
         "Usuário não encontrado"
    ]
}

I have tried many ways including from retrofit official website which uses this code

public class ErrorUtils {


public static APIError parseError(Response<JsonObject> response) {

    Converter<ResponseBody, APIError> converter =
            ServiceGenerator.retrofit()
                    .responseBodyConverter(APIError.class, new Annotation[0]);

    APIError error;

    try {
        error = converter.convert(response.errorBody());
    } catch (IOException e) {
        Log.v("LoginUser", "IOException -> " + e.getMessage());
        return new APIError();
    }

    return error;
}

public static class ServiceGenerator {
    public static final String API_BASE_URL = ApiClient.BASE_URL;

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    public static Retrofit retrofit = null;

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    public static Retrofit retrofit() {
        retrofit = builder.client(httpClient.build()).build();
        return retrofit;
    }
}}

API Error Class

public class APIError {
private String[] errors;

public String[] getErrors() {
    return errors;
}

public void setErrors(String[] errors) {
    this.errors = errors;
}

@Override
public String toString() {
    return "ClassPojo [errors = " + errors + "]";
}}

But in this way it goes into catch block of Error Utils class and the exception is

End of input at line 1 column 1 path $

Solution for this issue will be much appreciated. But keep this in mind that I have looked thoroughly on SO for both of these errors, then I post this question.

1

There are 1 answers

0
Malik Bilal On BEST ANSWER

Try this code in your onResponse Callback Method

                if (response.isSuccessful() && response.code() == 201) {

                      // Todo

                } else {

                    if (response.errorBody() != null) {

                        try {

                            JSONObject jsonObject = new JSONObject(response.errorBody().string());

                            JSONArray jsonArray = jsonObject.getJSONArray("errors");

                            List<String> errorStringList = new ArrayList<>();

                            for (int i = 0; i < jsonArray.length(); i++) {

                                errorStringList.add(jsonArray.get(i).toString());

                            }


                        } catch (JSONException | IOException e) {

                            e.printStackTrace();

                        }

                    }

                }

You can pass errorStringList to the instance of your ApiError


ApiError apiError = new ApiError();

apiError.setError(errorStringList.toArray(new String[0]))