Retrofit 2.0 java.lang.IllegalStateException:预期 BEGIN_ARRAY 但为 STRING

Retrofit 2.0 java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING

我在我的应用程序中使用 Retrofit 2.0。一切都很好,但是当我开始请求时,它 returns:

**java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING
at line 1 column 21 path $[0].iso**

这是我的 API 界面:

public interface GetPhones {
    @GET("phones.php")
    Call<ArrayList<Phones>> getPhones();
}

和型号class:

public class Phones {
    int id;
    char[] iso;
    String name;
    String phone_1;
    String phone_2;
    String phone_3;
}

片段中的代码:

Retrofit retrofit = new Retrofit.Builder()
         .baseUrl(URL_API)
         .client(SSLSuppressClient.trustcert())
         .addConverterFactory(GsonConverterFactory.create())
         .build();
GetPhones getPhonesInfo = retrofit.create(GetPhones.class);
Call<GetPhones> call = getPhonesInfo.getPhones();
call.enqueue(new Callback<GetPhones>() {
    @Override
    public void onResponse(Response<GetPhones> response, Retrofit retrofit) {
        Toast.makeText(getActivity(), "Success!", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(Throwable t) {
        Toast.makeText(getActivity(), "Failure!", Toast.LENGTH_SHORT).show();
        Log.d("LOG", t.getMessage());
                }
    });

问题似乎出在服务器端启用的 gzip 上。但是当我尝试使用 Response 编写代码时 - 它就像一个魅力。所以,问题不在于压缩。

Retrofit retrofit = new Retrofit.Builder()
             .baseUrl(URL_API)
             .client(SSLSuppressClient.trustcert())
             .addConverterFactory(GsonConverterFactory.create())
             .build();
GetPhones getPhonesInfo = retrofit.create(GetPhones.class);
Call<List<com.squareup.okhttp.Response>> call = getPhonesInfo.getPhones();
call.enqueue(new Callback<List<com.squareup.okhttp.Response>>() {
        @Override
        public void onResponse(Response response, Retrofit retrofit) {
             Toast.makeText(getActivity(), "Success!", Toast.LENGTH_SHORT).show();
             Log.d("LOG", response.message());
             Log.d("LOG", response.raw().toString());
}

        @Override
        public void onFailure(Throwable t) {
             Toast.makeText(getActivity(), "Failed!", Toast.LENGTH_SHORT).show();
             Log.d("LOG", t.getMessage());
        }
});

我哪里错了?

编辑:此答案对 Retrofit 2+ 无效。
查看 Retrofit 2 中的新功能:http://inthecheesefactory.com/blog/retrofit-2.0/


在这种情况下它可能对您没有帮助,但我在我的一个项目中遇到了同样的问题,解决方案是将 JSON 转换器设置为 Gson 的自定义实例。

将此添加到您的 Retrofit.Builder

.setConverter(new GsonConverter(new Gson()))


编辑: 它可能与 addConverterFactory() 冲突。除非你需要它并且知道为什么,否则我会把它拿出来。

正如 Pankaj Kumar 所设想的那样 - char[] iso 是问题所在。将类型更改为 String 解决了它!