kotlinx-serialization - Why default value inherited from base class is always encoded?

Viewed 707
@Serializable
open class A {
    val default: String = "hello"
}

@Serializable
open class B(val value: String): A()

fun main(){
    val obj = B("foo")
    val str = Json.encodeToString(obj)
    println(str)
}

encoding result:

{"default":"hello","value":"foo"}

Why the default value is encoded while the encodeDefaults config is false?

1 Answers

You might need to update the kotlinx-serialization library.

This is the code:

@Serializable
open class A {
    val default: String = "hello"
}

@Serializable
open class B(val value: String) : A()

private val json = Json { encodeDefaults = false }

fun main() {
    println(json.encodeToString(B("foo")))
}

This is the output:

{"value":"foo"}
Related