Search code examples
kotlinserializationkotlin-multiplatformktor

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("trwla@gmail.com", "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("trwla@gmail.com", "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?


Solution

  • 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