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

无法在Ktor Client中使用kotlinx.serialization问题求助

解决Ktor POST请求序列化异常问题

错误核心原因

报错提示Kotlin reflection is not available且无法序列化RegisterDto,本质是序列化依赖缺失/配置不完整,同时代码存在URL格式错误。

分步解决方案

1. 补全必要依赖(以Gradle Kotlin DSL为例)

确保项目包含对应依赖,版本需与你的Ktor、Kotlin版本匹配:

插件配置(build.gradle.kts)

plugins {
    kotlin("jvm") version "1.9.20" // 替换为项目使用的Kotlin版本
    kotlin("plugin.serialization") version "1.9.20" // 版本需与Kotlin版本完全一致
}

依赖配置(build.gradle.kts)

dependencies {
    // Ktor客户端核心
    implementation("io.ktor:ktor-client-core:2.3.7") // 替换为项目使用的Ktor版本
    implementation("io.ktor:ktor-client-cio:2.3.7")
    // 内容协商与JSON序列化
    implementation("io.ktor:ktor-client-content-negotiation:2.3.7")
    implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.7")
    // Kotlin反射依赖(解决反射不可用问题)
    implementation("org.jetbrains.kotlin:kotlin-reflect:1.9.20")
}

2. 修正URL格式错误

请求URL多了一个冗余斜杠,修改为:

url("http://192.168.0.104:8090/auth/login")

3. 验证序列化配置与客户端实例

  • 确保ApiClient.httpClient是你配置了ContentNegotiation的客户端实例,避免误用未配置序列化的默认客户端
  • 确认@Serializable注解来自kotlinx.serialization.Serializable包,而非其他第三方包:
import kotlinx.serialization.Serializable

@Serializable
data class RegisterDto(
    val email: String,
    val password: String
)

4. 检查IR编译器配置(Kotlin 1.8+)

若项目启用了Kotlin IR编译器,确保gradle.properties中无禁用序列化插件的配置:

kotlin.js.compiler=ir
kotlin.native.binary.memoryModel=experimental

验证修复

重新构建项目后再次发送请求,序列化异常即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 10:15:10