You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否将可序列化数据类作为Ktorfit的POST请求体?

解决Ktorfit中@Body数据类序列化错误

问题详情

  • 在Ktorfit中把@Body参数从String改为自定义数据类UserDto后,触发序列化异常
  • 接口代码:
@Headers("Content-Type: application/json")
@POST("login")
suspend fun login(@Body user: UserDto): String
  • 数据类代码:
@Serializable
data class UserDto(
    @SerialName("User") val userLogin: UserLogin
)

@Serializable
data class UserLogin(
    @SerialName("login_id") val loginId: String,
    val password: String
)
  • 抛出的错误:

Exception in thread "main" kotlinx.serialization.SerializationException: Serializer for class 'Any' is not found.
Mark the class as @Serializable or provide the serializer explicitly.

解决步骤

1. 添加必要依赖

以Gradle为例,在项目的build.gradle.kts中补充以下依赖:

// Ktorfit核心库
implementation("de.jensklingenberg.ktorfit:ktorfit-lib:1.10.0")
// Ktorfit的Kotlinx序列化转换器
implementation("de.jensklingenberg.ktorfit:ktorfit-converter-kotlinx-serialization:1.10.0")
// Kotlinx Json序列化核心库
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")

注意:版本号请根据你项目使用的Ktor版本同步调整。

2. 初始化Ktorfit时配置序列化转换器

创建Ktorfit实例时,必须通过HttpClient的ContentNegotiation插件配置Json序列化器,示例代码:

val ktorfit = Ktorfit.Builder()
    .baseUrl("你的API基础地址")
    .client(HttpClient(OkHttp) {
        install(ContentNegotiation) {
            json(Json {
                ignoreUnknownKeys = true // 可选:忽略响应中未定义的字段,避免解析失败
            })
        }
    })
    .build()

3. 确认数据类注解正确性

你当前的UserDto和UserLogin都已经添加了@Serializable注解,这部分无需修改,确保所有需要序列化的嵌套类都有该注解即可。

问题原因

这个错误本质是Ktorfit默认没有配置Json序列化转换器,无法识别带有@Serializable注解的数据类,导致框架尝试用默认逻辑处理时出现类型不匹配,进而抛出找不到Any类序列化器的异常。

内容的提问来源于stack exchange,提问作者csjr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 11:37:29