1
@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?

R.h
  • 60
  • 8

1 Answers1

1

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"}
LSafer
  • 344
  • 3
  • 7
  • Actually, I have tried to update the kotlinx-serialization library to the newest version, but it didn't work . I have already reported an issue to the koltinx.serialization team, and they recommended me to update kotlin version from 1.5.10 to 1.5.20 or higher(, and kotlin-serialization gradle plugin version as well, I think). Then everything works fine. I think the kotlin-serialization gradle plugin should be to blame. The serializer class generated by compiler plugin has changed after updating. Thank you anyway. – R.h Aug 26 '21 at 12:56