-
Type: Bug
-
Resolution: Unresolved
-
Priority: Major - P3
-
None
-
Affects Version/s: None
-
Component/s: Kotlin
I have a big data classes:
@Serializable sealed interface Sample { val fieldName: String } @Serializable @SerialName("sample1") data class SomeSample1( override val fieldName: String = "Im sample 1", val someMap: Map<String, Sample> = mutableMapOf() ) @Serializable @SerialName("sample2") data class SomeSample2(override val fieldName: String = "Im sample 2")
SerializersModule:
val serializersModule = SerializersModule { polymorphic(Sample::class) { subclass(SomeSample1::class) subclass(SomeSample2::class) } }
Registered codecs:
val someSample = KotlinSerializerCodec.create<Sample>(
serializersModule, BsonConfiguration(encodeDefaults = true)
)
val codecs = CodecRegistries.fromRegistries(
CodecRegistries.fromCodecs(*codecs), codecRegistry
)
In terms of standard Json.encode, this works fine. But if you use the ready-made version for BSON, it gives an error that SomeSample 1 is not registered in the polymophic hierarchy. This is a rather strange behavior, I tried not to use the sealed interface, specifying a class that has a field with a polymorphic value and there was still a mistake. The most interesting thing is if I package one of the classes into an object, and then pass it to KotlinSerializerCodec.create, then it will work. But I don't want to overwrite the entire element of the collection, I only need to overwrite the field in it.
Example:
@Serializable data class Profile( val name: String, val sample: Sample )
The sample needs to be overwritten, but the error I get does not allow it to be adequately implemented.
Stacktrace:
kotlinx.serialization.SerializationException: Class 'SomeSample1' is not registered for polymorphic serialization in the scope of 'Sample'. To be registered automatically, class 'SomeSample1' has to be '@Serializable', and the base class 'Nbt' has to be sealed and '@Serializable'. Alternatively, register the serializer for 'SomeSample1' explicitly in a corresponding SerializersModule. at kotlinx.serialization.internal.AbstractPolymorphicSerializerKt.throwSubtypeNotRegistered(AbstractPolymorphicSerializer.kt:102) ~[?:?] at kotlinx.serialization.internal.AbstractPolymorphicSerializerKt.throwSubtypeNotRegistered(AbstractPolymorphicSerializer.kt:114) ~[?:?] at kotlinx.serialization.PolymorphicSerializerKt.findPolymorphicSerializer(PolymorphicSerializer.kt:109) ~[?:?] at kotlinx.serialization.internal.AbstractPolymorphicSerializer.serialize(AbstractPolymorphicSerializer.kt:32) ~[?:?] at kotlinx.serialization.encoding.Encoder$DefaultImpls.encodeSerializableValue(Encoding.kt:279) ~[?:?] at kotlinx.serialization.encoding.AbstractEncoder.encodeSerializableValue(AbstractEncoder.kt:18) ~[?:?] at kotlinx.serialization.encoding.AbstractEncoder.encodeSerializableElement(AbstractEncoder.kt:80) ~[?:?]