数据类中的默认参数未使用 ktor 序列化程序转换为 json

Tar*_*wla 2 serialization kotlin ktor kotlin-multiplatform

在 http 请求中将数据类序列化为 json 时,我遇到了一个奇怪的问题。

工作代码:

@Serializable
data class ComanyCustomerLoginData(
  val email: String,
  val credential: String,
  val companyUUID: String,
)
val customerLoginData = ComanyCustomerLoginData("trwla@gmail.com", "1234", "d80f0b72-a062-11eb-bcbc-0242ac130002")
val response = client.post<HttpResponse>(URL) {
   contentType(ContentType.Application.Json)
   body = customerLoginData
}
Run Code Online (Sandbox Code Playgroud)

非工作代码

@Serializable
data class ComanyCustomerLoginData(
  val email: String,
  val credential: String,
  val companyUUID: String = "d80f0b72-a062-11eb-bcbc-0242ac130002",
)
val customerLoginData = ComanyCustomerLoginData("trwla@gmail.com", "1234")
val response = client.post<HttpResponse>(URL) {
   contentType(ContentType.Application.Json)
   body = customerLoginData
}
Run Code Online (Sandbox Code Playgroud)

在非工作代码中,在数据类构造函数中有一个默认参数,但是当它被序列化时,我在该 json 中看不到 companyUUID,但工作代码创建了一个名为 companyUUID 的键。

你能指出是什么问题吗?

Jof*_*rey 6

默认值默认情况下不编码kotlinx-serialization

文档中的这个地方描述了如何自定义此行为:

val format = Json { encodeDefaults = true }
Run Code Online (Sandbox Code Playgroud)

在Ktor中使用这个的具体情况,可以这样自定义:

install(JsonFeature) {
    serializer = KotlinxSerializer(kotlinx.serialization.json.Json {
        encodeDefaults = true
    })
}
Run Code Online (Sandbox Code Playgroud)

如果通信双方使用相同的数据模型,则您不需要它。他们都将正确使用默认值,并通过不明确写入来简单地节省带宽。