我目前正在开发一些我试图获得的基本应用程序 来自 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>
)
我的改造构建代码是:
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
return Retrofit.Builder()
.baseUrl(SERVER_BASE_URL)
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
我的要求很简单:
@GET("api/tags")
suspend fun getTags(): Deferred<Test>
但是当我调用 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)
已经尝试了很多其他方法都没有成功,可能是什么问题?
谢谢
最佳答案
这是因为您在一个函数中同时使用了 suspend
和 Deferred
。转换
@GET("api/tags")
suspend fun getTags(): Deferred<Test>
至
@GET("api/tags")
fun getTags(): Deferred<Test>
关于Android Kotlin 改造协程请求出现 moshi 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58036492/