使用多态序列化,我想序列化类 A、B1、B2。我想获得 B2 类的以下行
{"type":"type_2","baseField":"base_field_B","fieldB":true,"fieldB2":"field_B_2"}
我使用层次结构
interface BaseClass {
val baseField: String
}
@Serializable
@SerialName("type_1")
data class A(
override val baseField: String,
val fieldA: Int
) : BaseClass
@Serializable
@SerialName("type_2")
abstract class B: BaseClass{
abstract override val baseField: String
abstract val fieldB: Boolean
}
@Serializable
data class B1(
override val baseField: String,
override val fieldB: Boolean,
val fieldB1: Float
) : B()
@Serializable
data class B2(
override val baseField: String,
override val fieldB: Boolean,
val fieldB2: String
) : B()
并像这样进行序列化
Json(context = SerializersModule {
polymorphic(BaseClass::class) {
A::class with A.serializer()
B::class with B.serializer()
}
}).stringify(
PolymorphicSerializer(BaseClass::class),
B1("base_field_B", true, "field_B_2")
)
结果,我得到kotlinx.serialization.SerializationException: class B2 (Kotlin reflection is not available) is not registered for polymorphic serialization in the scope of interface BaseClass (Kotlin reflection is not available)
如何正确序列化给定的结构?B1、B2 类必须使用类型“type_2”进行序列化。