我有以下改装的单身人士:

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

MyResponse.kt

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

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.

我似乎找不到解决这个问题的办法..有什么提示吗?

EDIT:

The JSON response:

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

推荐答案

The problem is that you try to combine suspend with a Call<T> return type. When you use suspend you should make the Retrofit function return the data directly, like this:

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

Then all you have to do is to remove .await() when you make the call, like this:

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

Note that you should not use the MyResponse class at all since the JSON returns an array directly.

Kotlin相关问答推荐

如何将时间值格式化为00:00和00:00:00 Kotlin?""""

如何修改muableStateMapOf的值?

Kotlin 基于参数类型的返回类型推断

Kotlin 接口类型参数

Kotlin 如何使用其 get 函数在内部检索映射值

Kotlin:我可以将函数分配给 main 的伴随对象中的变量吗?

在 Kotlin 中,如何绑定扩展方法以在接收器范围函数中工作

如何在 kotlin 中使用带有泛型的密封类

我们应该在 Effect 和 Either 之间 Select 哪个作为我们业务服务的返回类型?

为 Gradle 子项目配置 Kotlin 扩展

Kotlin 代码是如何编译成原生代码的?

使用最新的 com.jakewharton.rxbinding3:rxbinding:3.0.0-alpha2 库时未找到 RxTextView 和其他小部件

runOnUiThread 没有调用

Kotlin Native如何将字节数组转换为字符串?

如何序列化/反序列化Kotlin密封类?

Lint 错误:可疑的相等判断:在 Object DiffUtilEquals 中未实现 equals()

通过在 kotlin-gradle 中使用子项目Unresolved reference: implementation

如何计算Kotlin中的百分比

旋转 kotlin 数组

使用 Kotlin 按字母对数组进行排序