造成这种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"

推荐答案

在Kotlin协程中,DeferredJob的一种类型,代表正在进行的协程.I think Retrofit支持Deferred,尽管我不记得使用过它.

翻新肯定支持suspend fun,这也有工作通过协程完成.

您的代码试图同时使用这两个函数:该函数声明为suspend fun and,它返回Deferred.这似乎是不必要的,因为您只需要一个来表示工作应该在协程中执行.

正如在问题 comments 中所讨论的,您移除了Deferred,问题也就消失了.由于suspend fun,您的网络I/O仍然将在协程中执行,使用Retrofit的默认调度程序.

Json相关问答推荐

如何抓住引号之间的第二次出现?

手动解开没有可编码的SON- Swift

在PowerShell中,如何获取数据对所在的JSON对象的名称

用于参考的Jolt变换

从Postgres表中的JSON中提取值

将pyspark.sql.Rowtype数据转换为Json字符串,消除Azure Databricks NB中的值

在 python 中循环 JSON 数组

Jolt 转换数组对象并将某些字段移动到嵌套数组

jq - 将父键值提取为子元素旁边的逗号分隔值

如何在jolt中使用shift和modify-overwrite-beta

如何在 Android Studio 中将 List 字段作为空列表[]返回?

使用 BASH 和 JQ 我想将 json 文件与 bash 数组进行比较

如果有 1 个元素,如何防止 ConvertFrom-Json 折叠嵌套数组

如何将动态复杂 json 解析为dart 对象或模型

在自定义 JsonConverter 的 ReadJson 方法中处理空对象

json_encode() 返回 false

为不同类型的项目数组正确的 JSON Schema

如何访问 JSON 对象数组的第一个元素?

[__NSCFNumber 长度]:发送到实例 UITableView 的无法识别的 Select 器

如何从 MVC 控制器返回 Json 对象以查看