0

Why JSON doesn't content property with default value?

I suppose that is serialized only what is actually needed to rebuild object, but is totally useless when i just want create API JsonResponses...

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.encodeToJsonElement

@Serializable
data class Test(
    val required: String,
    val defaulted: String = "default",
)


val test = Test(
   required = "set"
)

println(Json.encodeToJsonElement(test))

// Result= {"required":"set"}
aSemy
  • 5,485
  • 2
  • 25
  • 51
WhipsterCZ
  • 638
  • 1
  • 8
  • 13

1 Answers1

1

The reason given in the documentation is to avoid visual clutter.

As explained in the documentation here, you can mark properties that have defaults with @EncodeDefault if you want them to be included in the JSON:

@Serializable
data class Test(
    val required: String,
    @EncodeDefault val defaulted: String = "default",
)

Or, if you want to do this everywhere without the annotation, create a customized Json encoder like this (documentation here):

val encodeDefaultsJson = Json { encodeDefaults = true }
println(encodeDefaultsJson.encodeToJsonElement(test))
Tenfour04
  • 83,111
  • 11
  • 94
  • 154