mic*_*123 2 java android gson retrofit
我在我的应用程序中使用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.
Run Code Online (Sandbox Code Playgroud)
这是我的API接口:
public interface GetPhones {
@GET("phones.php")
Call<ArrayList<GetPhones>> getPhones();
}
Run Code Online (Sandbox Code Playgroud)
和模型类:
public class GetPhones {
int id;
char[] iso;
String name;
String phone_1;
String phone_2;
String phone_3;
}
Run Code Online (Sandbox Code Playgroud)
和代码片段:
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());
}
});
Run Code Online (Sandbox Code Playgroud)
我试图为GetPhones.class制作无参数的构造函数,但它没有任何改变。
Dan*_*son 15
如果2019年有人遇到此问题并使用Kotlin,协程和至少Retrofit 2.6.0,Call<MyObject>则在api方法为时返回实例suspended会产生相同的错误消息,这有点令人困惑。
解决方案是在接口定义中替换Call<MyObject>为MyObject,然后?.execute()?.body()在呼叫站点删除(或等效方法)。
编辑:
我认为大多数人会偶然发现这一点的原因是,他们希望将暂停的改装响应包装成某种形式,以无缝方式处理错误。
有对这个问题设在这里,或许改造将在未来解决这个问题。我最终使用了这里提供的那种解决方案。
interface GetPhones接口 ( ) 和模型类 ( )具有相同的名称class GetPhones。
我认为您正在使用这一行的接口:
Call<ArrayList<GetPhones>> getPhones();
Run Code Online (Sandbox Code Playgroud)
但它应该是你的模型类。检查它的导入部分或重命名模型类以确保您没有混合它。
| 归档时间: |
|
| 查看次数: |
3666 次 |
| 最近记录: |