Android Kotlin 改造协程请求出现 moshi 错误

Gla*_*adi 2 android kotlin retrofit moshi

我目前正在开发一些基本的应用程序,我尝试从 API - 对象列表中获取响应。

我的数据类是:

@JsonClass(generateAdapter = true)
data class Tag(
    @Json(name = "id")
    val id: Int,
    @Json(name = "name")
    val name: String
)

@JsonClass(generateAdapter = true)
data class Test(
    @Json(name = "count")
    val count: Int,
    @Json(name = "next")
    val next: Int,
    @Json(name = "previous")
    val previous: Int,
    @Json(name = "results")
    val results: List<Tag>
)
Run Code Online (Sandbox Code Playgroud)

我的改造构建代码是:

val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()

return Retrofit.Builder()
    .baseUrl(SERVER_BASE_URL)
    .addCallAdapterFactory(CoroutineCallAdapterFactory())
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .build()
Run Code Online (Sandbox Code Playgroud)

而我的要求也很简单:

@GET("api/tags")
suspend fun getTags(): Deferred<Test>
Run Code Online (Sandbox Code Playgroud)

但是当我打电话时getTags()出现以下错误:

java.lang.IllegalArgumentException: Unable to create converter for kotlinx.coroutines.Deferred<com.example.kotlin_ex2.models.Test>
     Caused by: java.lang.IllegalArgumentException: No JsonAdapter for kotlinx.coroutines.Deferred<com.example.kotlin_ex2.models.Test> (with no annotations)
Run Code Online (Sandbox Code Playgroud)

已经尝试了很多其他方法都没有成功,可能是什么问题?

谢谢

hos*_*ini 5

这是因为您在一个函数中同时使用了suspend和。Deferred转变

@GET("api/tags")
suspend fun getTags(): Deferred<Test>
Run Code Online (Sandbox Code Playgroud)

@GET("api/tags")
fun getTags(): Deferred<Test>
Run Code Online (Sandbox Code Playgroud)