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

Default parameter in data class not converted to json using ktor serializer

我在 http 请求中将数据 class 序列化为 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
}

无效代码

@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
}

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

能否指出问题所在?

默认值 are not encoded 默认为 kotlinx-serialization:

This place in the docs 描述了如何自定义此行为:

val format = Json { encodeDefaults = true }

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

install(JsonFeature) {
    serializer = KotlinxSerializer(kotlinx.serialization.json.Json {
        encodeDefaults = true
    })
}

如果通信的双方使用相同的数据模型,那么您应该不需要这个。他们都将正确使用默认值,并通过不显式写入来简单地节省带宽。


编辑:这里是你如何在 Ktor 2.0 中配置同样的东西:

install(ContentNegotiation) {
    json(Json {
        encodeDefaults = true
    })
}

https://ktor.io/docs/serialization-client.html#register_json

你需要encodeDefaults = true 有关详细信息,请参阅 this issue