-
Type: Bug
-
Resolution: Duplicate
-
Priority: Major - P3
-
None
-
Affects Version/s: 5.0.1
-
Component/s: Kotlin
-
None
-
Java Drivers
Serialization of sealed classes lacks type fieldĀ _t.
This code throws SerializationException on the last line:
class MyTest { @Serializable sealed class MyClass { abstract val myInt: Int abstract val myString: String } @Serializable data class MyClass1(override val myInt: Int, override val myString: String, val myLong: Long) : MyClass() @Serializable data class MyClass2(override val myInt: Int, override val myString: String, val myInstant: Instant) : MyClass() @Test fun storeAndRetrieveSealedClasses() = runTest { val client = MongoClient.create("mongodb://localhost") val mongoDatabase = client.getDatabase("MyTest") val document1 : MyClass = MyClass1(0, "a", 3) val document2 : MyClass = MyClass2(0, "b", Instant.parse("2023-01-01T12:13:14Z")) // Sanity test assertThat(Json.decodeFromString<MyClass>(Json.encodeToString(document1))).isEqualTo(document1) assertThat(Json.decodeFromString<MyClass>(Json.encodeToString(document2))).isEqualTo(document2) val c = mongoDatabase.getCollection<MyClass>("Test") c.insertOne(document1) c.insertOne(document2) val result = c.find().toList() // This line throws } }
Thrown exception:
kotlinx.serialization.SerializationException: Missing required discriminator field `_t` for polymorphic class: `MyTest.MyClass`.
Using versions:
- org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.3
- org.mongodb:bson-kotlinx:5.1.0
- org.mongodb:mongodb-driver-kotlin-coroutine:5.0.1
As you can see in the beginning of the test, serialization to JSON correctly includes the discriminator field and is able to deserialize.
- duplicates
-
JAVA-5304 bson-kotlinx & polymorphic MongoCollection instances
- Closed