gpt4 book ai didi

kotlin - 我可以使用具有多个密封类级别的 kotlinx 序列化器作为父类和嵌套调用吗?

转载 作者:行者123 更新时间:2023-12-05 05:59:33 24 4
gpt4 key购买 nike

我正在尝试使用 kotlinx @Serializable,我遇到了这个问题:

我有以下类(class):

@Serializable
sealed class GrandParent

第二个:

@Serializable
sealed class Parent() : GrandParent() {
abstract val id: String
}

还有第三个

@Serializable
data class Child(
override val id: String, ....
): Parent()

我需要祖 parent ,因为我在另一个类中将其用作泛型类型,而该类恰好也引用了祖 parent 类

@Serializable
data class MyContent(
override val id: String,
....
val data: GrandParent, <- so it has a self reference to hold nested levels
...): Parent()

每次我尝试运行它时都会出现错误...

Class 'MyContent' is not registered for polymorphic serialization in the scope of 'GrandParent'.
Mark the base class as 'sealed' or register the serializer explicitly.

我使用 ktor 作为包装器,kotlin 1.5.10。我是根据 https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#registered-subclasses 做的

有什么想法吗?

最佳答案

您应该使用密封类进行序列化和反序列化,以便 kotlin 序列化“知道”添加具有正确实现的鉴别器。默认情况下,它会在 json 中搜索 type,但您可以使用 JsonBuilder 更改它:

Json {
classDiscriminator = "class"
}

这是一个例子:

@Serializable
sealed class GrandParent

@Serializable
sealed class Parent : GrandParent() {
abstract val id: String,
}

@Serializable
data class Child(
override val id: String,
): Parent()

@Serializable
data class MyContent(
override val id: String,
val data: GrandParent,
): Parent()

fun main() {
val test = MyContent(id = "test", data = Child(id = "child"))

val jsonStr = Json.encodeToString(GrandParent.serializer(), test)
println("Json string: $jsonStr")

val decoded = Json.decodeFromString(GrandParent.serializer(), jsonStr)
println("Decoded object: $decoded")
}

控制台结果:

Json string: {"type":"MyContent","id":"test","data":{"type":"Child","id":"child"}}
Decoded object: MyContent(id=test, data=Child(id=child))

encode和decode也可以这样写(不过背后会用到反射):

val jsonStr = Json.encodeToString<GrandParent>(test)
println("Json string: $jsonStr")

val decoded = Json.decodeFromString<GrandParent>(jsonStr)
println("Decoded object: $decoded")

关于kotlin - 我可以使用具有多个密封类级别的 kotlinx 序列化器作为父类和嵌套调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68084176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com