OkHttp / Retrofit / Gson:预期 BEGIN_OBJECT 但 BEGIN_ARRAY

OkHttp / Retrofit / Gson: Expected BEGIN_OBJECT but was BEGIN_ARRAY

我有这个

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

同时尝试从 API 检索数据。我正在使用 Retrofit、Gson 和 OkHttpClient。 我正在尝试将来自字符 (API: http://hp-api.herokuapp.com/api/characters/house/gryffindor) 的数据显示到 RecyclerView 中。

这是我的代码,希望您能找到任何线索:

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

我的网络服务客户端:

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

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

这是我的数据class(对于 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;
    }
}

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

正如错误明确指出的那样,您正在尝试将 JSONArray 解析为 JSONObject

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

此服务方法需要 JSONObject,但根据图中共享的 logcat,响应是给 JSONArray。相反,您应该将其解析为:

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

似乎没有充分的理由在此处使用您的数据 class(class 被非常笼统地称为“数据”这一事实似乎反映了这一点)。您收到多个 Personaje,因此您应该接受多个 Personaje:

    Call<List<Personaje>> getPersonajes(@Path("house") String house);

如果您使用数据 class,(没有列表),反序列化器将需要一个对象,因此会出现错误 (Expected BEGIN_OBJECT)。如果您在数据中实现列表,您 可能 能够让它工作,但是当 Call<List<Personaje>> getPersonajes 应该可以正常工作时,它似乎没有任何代码。