Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am facing a weird issue while serializing a data class to json in an http request.

Working code:

@Serializable
data class ComanyCustomerLoginData(
  val email: String,
  val credential: String,
  val companyUUID: String,
)
val customerLoginData = ComanyCustomerLoginData("[email protected]", "1234", "d80f0b72-a062-11eb-bcbc-0242ac130002")
val response = client.post<HttpResponse>(URL) {
   contentType(ContentType.Application.Json)
   body = customerLoginData
}

Non working code

@Serializable
data class ComanyCustomerLoginData(
  val email: String,
  val credential: String,
  val companyUUID: String = "d80f0b72-a062-11eb-bcbc-0242ac130002",
)
val customerLoginData = ComanyCustomerLoginData("[email protected]", "1234")
val response = client.post<HttpResponse>(URL) {
   contentType(ContentType.Application.Json)
   body = customerLoginData
}

In the non working code, in data class constructor there is one default parameter but when its serialized I don't see companyUUID in that json but working code creates a key named companyUUID.

can you please point out what is the issue?

like image 801
Tarun Chawla Avatar asked Jul 11 '26 11:07

Tarun Chawla


2 Answers

Default values are not encoded by default in kotlinx-serialization:

This place in the docs describes how you can customize this behaviour:

val format = Json { encodeDefaults = true }

In the specific case of using this in Ktor, you can customize it this way:

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

If both sides of the communication use the same data model, you shouldn't need this though. They will both use the default value properly and simply save bandwidth by not writing it explicitly.


EDIT: here is how you would configure this same thing in Ktor 2.0:

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

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

like image 165
Joffrey Avatar answered Jul 14 '26 11:07

Joffrey


You need encodeDefaults = true See this issue for more information

like image 33
Róbert Nagy Avatar answered Jul 14 '26 10:07

Róbert Nagy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!