如何使用 kotlinx 序列化通过 open val 序列化 kotlin 密封类

Boh*_*nko 9 serialization kotlin kotlinx.serialization

import kotlinx.serialization.Serializable

@Serializable
sealed class Exercise(open val id: String) {

    @Serializable
    data class Theory(override val id: String) : Exercise(id)
}
Run Code Online (Sandbox Code Playgroud)

我的代码中有这样的密封类,编译器告诉我: Serializable class has duplicate serial name of property 'id', either in the class itself or its supertypes

有没有办法在可序列化的密封类中拥有 open val,在覆盖它时可以正常工作?

Oli*_* O. 13

这是Kotlin 问题 KT-38958。这似乎是构造函数属性要求的一个极端情况。

可以通过使用以下实现来解决,

import kotlinx.serialization.*
import kotlinx.serialization.json.Json

@Serializable
sealed class Exercise {
    abstract val id: String

    @Serializable
    data class Theory(override val id: String) : Exercise()
}

fun main() {
    val t1 = Exercise.Theory("t1")
    val t1Json = Json.encodeToString(t1)
    println(t1Json)
    println(Json.decodeFromString<Exercise.Theory>(t1Json).toString())
}
Run Code Online (Sandbox Code Playgroud)

这将输出:

{"id":"t1"}
Theory(id=t1)
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅《Kotlin 序列化指南》中的“设计可序列化层次结构” 。