How to serialize Kotlin data-class with default values into JSON using kotlinx.serialization?

Viewed 2757

There is an example of a class with a default value:

@Serializable
data class TestClass(
    val obligatory: String,
    val optional: Int = 0
)

It can be correctly deserialize from jsons like: { "obligatory":"text", "optional":1 } and { "obligatory":"text" }.
At the same time, the result of its serialization has to contain the attribute "optional".

As a result of serialization:

Json.encodeToString(TestClass("text"))

I expect { "obligatory":"text", "optional":0 }, however now I have { "obligatory":"text" }.

How should I change my code to achieve the expected result?

1 Answers
Related