导致此 Kotlin Retrofit2 错误的可能原因有哪些?

问题描述 投票:0回答:1

导致此 Kotlin Retrofit2 错误的可能原因有哪些?当我使用 enqueue 对其进行编码时,我的 JSON 转换正确。我将其更新为使用延迟和响应,但现在收到此错误。

Unable to create converter for kotlinx.coroutines.Deferred<retrofit2.Response<com.smate.data.apiResponse.GenericApiResponse>>

它指的是我的代码的这一部分:

@Headers("Content-Type: application/json")
@POST("validIdentification")
suspend fun isValidIdentificationAsync(@Body identification: Identification): Deferred<Response<GenericApiResponse>>

这是 GenericApiResponse 类:

package com.smate.data.apiResponse

import kotlinx.serialization.Serializable

@Serializable
data class GenericApiResponse(
    var isValid:String
) {
    val isValidBoolean: Boolean
        get() = isValid.toBoolean()
}

这是调用函数:

override suspend fun isValidIdentification(identification: Identification): ValidationResult {
    try {
        val response = sMateApiService.isValidIdentificationAsync(identification).await()
        if (response.isSuccessful) {
            val genericResponse: GenericApiResponse? = response.body()
            if (genericResponse != null) {
                return ValidationResult.Success(genericResponse.isValidBoolean)
            }
        } else {
            return ValidationResult.Error("API call failed")
        }
    } catch (e: Exception) {
        return ValidationResult.Error("An error occurred: ${e.message}")
    }

    return ValidationResult.Error("Unexpected error")
}

我正在我的 gradle 文件中实现这些:

implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0"
android json kotlin retrofit2 jetbrains-ide
1个回答
0
投票

在 Kotlin 协程中,

Deferred
Job
的一种,代表正在进行的协程。我认为Retrofit 支持
Deferred
,尽管我不记得使用过它。

Retrofit 肯定支持

suspend fun
,它也可以通过协程完成工作。

您的代码尝试同时使用两者:该函数被声明为

suspend fun
并且 它返回
Deferred
。这似乎没有必要,因为您只需要一个来表示工作应该在协程中执行。

正如问题评论中所讨论的,您删除了

Deferred
,问题就消失了。由于
suspend fun
,您的网络 I/O 仍将使用 Retrofit 的默认调度程序在协程中执行。

© www.soinside.com 2019 - 2024. All rights reserved.