JsonIOException:接口无法实例化!为此类型注册 InstanceCreator 或 TypeAdapter。接口名称:改造2。叫



我正在使用用户名和密码参数进行post-call。实际调用正在工作,HTTP响应成功,但返回以下错误:

误差

com.google.gson.JsonIOException: Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for this type. Interface name: retrofit2.Call
W/System.err:     at com.google.gson.internal.ConstructorConstructor$3.construct(ConstructorConstructor.java:136)
W/System.err:     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$FieldReflectionAdapter.createAccumulator(ReflectiveTypeAdapterFactory.java:427)
W/System.err:     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:383)
W/System.err:     at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:40)
W/System.err:     at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27)
W/System.err:     at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:243)
W/System.err:     at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:153)
W/System.err:     at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)

服务
@FormUrlEncoded
@POST("login")
suspend fun authenticateUser(@Field("email") email: String, @Field("password") password: String): Call<LoginResponse>

TL;

Response代替Call

详细信息你在这里混合了悬挂风格和基于Call的Retrofit用法:

  • 如果您想从使用挂起方法中获益(提示:您确实这样做),authenticateUser的返回类型应该是Response<LoginResponse>而不是Call<LoginResponse>:
@FormUrlEncoded
@POST("login")
suspend fun authenticateUser(@Field("email") email: String, @Field("password") password: String): Response<LoginResponse>
  • 如果你想使用Retrofit的Call,你应该使它不可挂起,并使用Call::enqueue(异步调用)或Call::execute(同步调用):
@FormUrlEncoded
@POST("login")
fun authenticateUser(@Field("email") email: String, @Field("password") password: String): Call<LoginResponse>

...
// Somewhere
//This
val loginResponse = authenticateUser("email", "password).execute() // throws IOException upon problem talking to the server
// Or this
authenticateUser("email", "password).enqueue(object:Callback<LoginResponse>{
override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) {
// It worked!
}
override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
// Something went wrong
}
})

  • Retrofit 2.6.0版本变更日志(引入suspend支持)
  • 改造的网页
  • 改造的javadoc

相关内容

  • 没有找到相关文章

最新更新