gpt4 book ai didi

java - Retrofit 2.0 + GSON 无法为接口(interface)调用无参数构造函数

转载 作者:行者123 更新时间:2023-12-01 10:04:05 25 4
gpt4 key购买 nike

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

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 接口(interface):
public interface GetPhones {
@GET("phones.php")
Call<ArrayList<GetPhones>> getPhones();
}

和模型类:
public class GetPhones {
int id;
char[] iso;
String name;
String phone_1;
String phone_2;
String phone_3;
}

和 fragment 中的代码:
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 创建无参数构造函数,但它并没有改变任何东西。

最佳答案

如果 2019 年有人遇到此问题并使用 Kotlin、协程和至少 Retrofit 2.6.0,则返回 Call<MyObject> api方法为suspended的实例,产生相同的错误消息,这有点令人困惑。

解决方法是更换Call<MyObject>MyObject在接口(interface)定义中,删除?.execute()?.body() (或等效)在调用站点。

编辑:

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

有一个问题 located here ,也许Retrofit 将来会处理这个问题。我最终使用了 kind solution provided here .

关于java - Retrofit 2.0 + GSON 无法为接口(interface)调用无参数构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33749752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com