Search code examples
javaandroidgsonretrofit2

OkHttp / Retrofit / Gson: Expected BEGIN_OBJECT but was BEGIN_ARRAY


I am having this

Error: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

while trying to retreive data from an API. I am using Retrofit, Gson and OkHttpClient. I am trying to display data from characters (API: http://hp-api.herokuapp.com/api/characters/house/gryffindor) into a RecyclerView.

This is my code, I hope you can find with any clue of what's happening:

private void lanzarPeticion(String house) {
    loggingInterceptor = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
    httpClientBuilder = new OkHttpClient.Builder().addInterceptor(loggingInterceptor);

    retrofit = new Retrofit.Builder().baseUrl("http://hp-api.herokuapp.com/api/")
            .addConverterFactory(GsonConverterFactory.create())
            .client(httpClientBuilder.build())
            .build();

    WebServiceClient client = retrofit.create(WebServiceClient.class);

    Call<Data> call = client.getPersonajes(house);
    call.enqueue(new Callback<Data>() {
        @Override
        public void onResponse(Call<Data> call, Response<Data> response) {
            adapter.setPersonajes(response.body().getResults());
        }

        @Override
        public void onFailure(Call<Data> call, Throwable t) {
            Log.d("TAG1", "Error: " + t.getMessage());
        }
    });
}

My WebServiceClient:

public interface WebServiceClient {
    @GET("characters/house/{house}")
    Call<Data> getPersonajes(@Path("house") String house);

    @GET()
    Call<Personaje> getPersonaje(@Url String url);
}

This is my Data class (for the getResults())

public class Data {
    private String count;
    private String next;
    private List<Personaje> results;

    public String getCount() {
        return count;
    }

    public void setCount(String count) {
        this.count = count;
    }

    public String getNext() {
        return next;
    }

    public void setNext(String next) {
        this.next = next;
    }

    public List<Personaje> getResults() {
        return results;
    }

    public void setResults(List<Personaje> results) {
        this.results = results;
    }
}

enter image description here


Solution

  • Error: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

    As the error clearly says, you are trying to parse JSONArray into a JSONObject

    @GET("characters/house/{house}")
    Call<Data> getPersonajes(@Path("house") String house);
    

    This service method expecting JSONObject, but according the logcat shared by in the image, the response is giving JSONArray. Instead you should parse it as:

    @GET("characters/house/{house}")
    Call<List<Personaje>> getPersonajes(@Path("house") String house)