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

Ktor 1.6.3向Django REST API发POST请求时序列化失败

问题解决方案

核心问题分析

你遇到的序列化失败错误,主要源于两个关键问题:

  • 数据类未添加序列化注解,导致Kotlinx Serializer无法识别并处理
  • createUser方法中重新创建了未配置任何特性的空HttpClient实例,而非复用你已经安装JsonFeature的客户端

分步修复

1. 给数据类添加序列化注解

所有需要进行序列化/反序列化的数据类必须添加@Serializable注解,同时导入正确的包:

import kotlinx.serialization.Serializable

@Serializable
data class UserPostResponse (
    val activation: String
)

@Serializable
data class UserPostRequest(
    val username: String,
    val email: String,
    val password: String,
    val password_check: String
)

2. 复用配置好的HttpClient实例

你的createUser方法里重新创建了HttpClient(),这个实例没有安装JsonFeature,自然无法序列化请求体。修改代码,复用已配置好的客户端:

// 先在类中初始化配置完成的client
private val client = HttpClient(Android) {
    install(Logging) {
        level = LogLevel.ALL
    }

    install(JsonFeature) {
        serializer = KotlinxSerializer(kotlinx.serialization.json.Json {
            prettyPrint = true
            isLenient = true
            acceptContentTypes = listOf(ContentType.Any)
        })
    }
}

override suspend fun createUser(postRequest: UserPostRequest): UserPostResponse? {
    return try {
        client.post<UserPostResponse> {
            url(HttpRoutes.REGISTER)
            contentType(ContentType.Application.Json)
            body = postRequest
        }
    } catch (exception: ClientRequestException) {
        println("ClientError: ${exception.response.status.description}")
        null
    } catch (exception: Exception) {
        println("Error: ${exception.message}")
        null
    }
}

3. 确认依赖完整性

确保Module级别的build.gradle中包含Ktor 1.6.3对应的序列化依赖:

// Kotlinx Serialization
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0"

// Ktor客户端序列化相关
implementation "io.ktor:ktor-client-serialization:1.6.3"
implementation "io.ktor:ktor-client-json:1.6.3"

注意:kotlinx-serialization版本需与你使用的Kotlin版本匹配(Kotlin 1.6.x对应serialization 1.3.x)。

额外验证点

  • 确认Django接口的响应字段名是activation(你代码中写的是activation,错误提示里Django返回的是Actuvation,注意拼写是否一致,避免反序列化失败)
  • 检查Django接口是否支持解析application/json格式的请求体

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:17:21