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

标签 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>
)

我的改造构建代码是:

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)

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

谢谢

最佳答案

这是因为您在一个函数中同时使用了 suspendDeferred。转换

@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/

相关文章:

kotlin - 使用 measureTimeMillis 的运行时

android - CoroutineScope的范围是什么?

java - Android - 改造 : Error getting a response. Gson 错误

android - 使用 MockWebServer 运行测试总是调用失败回调(连接异常)

android - 为什么使用 Retrofit 从服务器到本地数据库同步大量数据时 Android Circle Progress 对话框会卡住

android - 软键盘打开时不要缩小 ImageView 或背景

android - 在 2 行 Gridview 之间添加 View

android - 如何画一个透明的圆圈?

android - 无法在 androidx.appcompat.widget.TintContextWrapper 中为 MaterialButton 中的 onClick 处理程序找到自定义方法

spring-boot - Spring WebFlux Reactive 和 Kotlin Coroutines 启动报错