Retrofit 2.0 + GSON 无法为接口调用无参数构造函数

Retrofit 2.0 + GSON Unable to invoke no-args constructor for interface

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

Unable to invoke no-args constructor for interface
com.example.project.API.GetPhones. Register an InstanceCreator
with Gson for this type may fix this problem.

这是我的 API 界面:

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

和型号class:

public class GetPhones {
    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());
                }
    });

我尝试为 GetPhones.class 创建无参数构造函数,但它没有改变任何东西。

接口 (interface GetPhones) 和模型 class (class GetPhones) 的名称相同。

我认为您在这一行中使用了界面:

Call<ArrayList<GetPhones>> getPhones();

不过应该是你的模特class。检查它的导入部分或重命名模型 class 以确保您没有混合它。

如果 2019 年有人遇到这个问题并且正在使用 Kotlin、协程和至少 Retrofit 2.6.0,则在 api 方法为 suspended 时返回一个 Call<MyObject> 实例,生成同样的错误信息,有点迷惑。

解决方法是将接口定义中的Call<MyObject>替换为MyObject,并在调用处去掉?.execute()?.body()(或等效)

编辑:

我认为大多数人会偶然发现这一点的原因是他们想将暂停的 Retrofit 响应包装在某种东西中以无缝处理错误。

这里有一个问题 located here, perhaps Retrofit will deal with this in the future. I ended up using the

这真的很有帮助。我有同样的问题,它通过在我们为 API 调用请求编写函数的界面中将 Call<MyObject> 替换为 MyObject,然后在调用站点删除 .enque 来工作.