kotlinx.serialization 为什么不会忽略从父类继承的带有默认值的属性?


#1

这是官方文档 Polymorphism # Concrete properties in a base class 中的示例:

@Serializable
sealed class Project {
    abstract val name: String
    var status = "open"
}

@Serializable
@SerialName("owned")
class OwnedProject(override val name: String, val owner: String) : Project()

fun main() {
    val json = Json { encodeDefaults = true } // "status" will be skipped otherwise
    val data: Project = OwnedProject("kotlinx.coroutines", "kotlin")
    println(json.encodeToString(data))
}

如果将示例中的encodeDefaults 设置为false,输出的Json 字符串还是会包含status 属性:

{“type”:“owned”,“status”:“open”,“name”:“kotlinx.coroutines”,“owner”:“kotlin”}


#2

更新Kotlin 和编译插件版本后,问题解决


京ICP备16022265号-2 Kotlin China 2017 - 2018