首页 > 解决方案 > 无法为 retrofit2.Call 调用无参数构造函数

问题描述

我有以下改造单例:

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 )
        }
    }
}

我的响应.kt

data class MyResponse(
    val listOfData: List<DataEntity>
)

数据实体.kt

data class DataEntity(
    @SerializedName("name")
    val fullName: String
}

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

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

但我不断得到:

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.

我似乎无法找到解决这个问题的方法。请给点提示?

编辑:

JSON 响应:

[
    {
    "name": "A"
    },
    {
    "name": "B"
    },
    {
    "name": "C"
    }
]

标签: kotlinretrofit

解决方案


问题是您尝试suspendCall<T>返回类型结合使用。使用suspend时,应该让 Retrofit 函数直接返回数据,如下所示:

suspend fun fetchData() : List<DataEntity> // Note: Not MyResponse, see below

然后,您所要做的就是.await()在拨打电话时删除,如下所示:

// Will throw exception unless HTTP 2xx is returned
val webResponse = MyAPI.create().fetchData()

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


推荐阅读