无法为 retrofit2.Call 调用无参数构造函数

0x2*_*29a 7 kotlin retrofit

我有以下改造单身人士:

interface MyAPI
{
    @GET("/data.json")
    suspend fun fetchData() : Call<MyResponse>

    companion object
    {
        private val BASE_URL = "http://10.0.2.2:8080/"

        fun create(): MyAPI
        {
            val gson = GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                .create()

            val retrofit = Retrofit.Builder()
                .addConverterFactory( GsonConverterFactory.create( gson ) )
                .baseUrl( BASE_URL )
                .build()

            return retrofit.create( MyAPI::class.java )
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

MyResponse.kt

data class MyResponse(
    val listOfData: List<DataEntity>
)
Run Code Online (Sandbox Code Playgroud)

数据实体.kt

data class DataEntity(
    @SerializedName("name")
    val fullName: String
}
Run Code Online (Sandbox Code Playgroud)

我通过以下方式从 ModelView 调用代码:

viewModelScope.launch {
    try {
        val webResponse = MyAPI.create().fetchData().await()
        Log.d( tag, webResponse.toString() )
    }
    catch ( e : Exception )
    {
        Log.d( tag, "Exception: " + e.message )
    }
}
Run Code Online (Sandbox Code Playgroud)

但我不断得到:

Unable to invoke no-args constructor for retrofit2.Call<com.host.myproject.net.response.MyResponse>. Registering an InstanceCreator with Gson for this type may fix this problem.
Run Code Online (Sandbox Code Playgroud)

我似乎无法找到解决此问题的方法.. 有什么提示吗?

编辑:

JSON 响应:

[
    {
    "name": "A"
    },
    {
    "name": "B"
    },
    {
    "name": "C"
    }
]
Run Code Online (Sandbox Code Playgroud)

Ens*_*lic 28

问题是您尝试suspendCall<T>返回类型结合使用。使用的时候suspend应该让 Retrofit 函数直接返回数据,像这样:

suspend fun fetchData() : List<DataEntity> // Note: Not MyResponse, see below
Run Code Online (Sandbox Code Playgroud)

然后你要做的就是.await()在你打电话的时候删除,就像这样:

// Will throw exception unless HTTP 2xx is returned
val webResponse = MyAPI.create().fetchData()
Run Code Online (Sandbox Code Playgroud)

请注意,您根本不应使用MyResponse该类,因为 JSON 直接返回一个数组。

  • 你如何添加错误处理呢?我想使用“Call”,因为直接使用数据时我无法控制错误。 (2认同)
  • 您可以通过捕获 HttpException 来处理错误,该异常是由改进框架针对非 HTTP 200 左右的响应代码引发的。 (2认同)

cre*_*der 8

第 1 步:删除呼叫并处理响应

前:

@POST("list")
    suspend fun requestList(@Body body: JsonObject): call<Profile>
Run Code Online (Sandbox Code Playgroud)

@POST("list")
    suspend fun requestList(@Body body: JsonObject): Profile
Run Code Online (Sandbox Code Playgroud)

步骤2:删除挂起并处理响应

 @POST("list")
     fun requestList(@Body body: JsonObject): call<Profile>
Run Code Online (Sandbox Code Playgroud)


小智 7

我有同样的问题,检查我的模型没问题后。然后我尝试删除接口 API 上的挂起。

@GET("/data.json")
suspend fun fetchData() : Call<MyResponse>
Run Code Online (Sandbox Code Playgroud)

成为

@GET("/data.json")
fun fetchData() : Call<MyResponse>
Run Code Online (Sandbox Code Playgroud)

它解决了(错误 Unable to invoke no-args constructor for Retrofit2.Call 已经消失)。