Android Kotlin 改造协程请求出现 moshi 错误
Android Kotlin retrofit coroutine requests with moshi error
我目前正在开发一些我试图获得的基本应用程序
来自 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>
已解决。
如我所见,我只需要删除 Deferred class 并这样写:
@GET("api/tags")
suspend fun getTags(): Test
并且无需从协程内部调用 await()
。
我目前正在开发一些我试图获得的基本应用程序 来自 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>
已解决。 如我所见,我只需要删除 Deferred class 并这样写:
@GET("api/tags")
suspend fun getTags(): Test
并且无需从协程内部调用 await()
。