Litote / kmongo

[deprecated] KMongo - a Kotlin toolkit for Mongo
https://litote.org/kmongo/
Apache License 2.0
781 stars 75 forks source link

ERROR: 'WrappedObjectId' is not registered for polymorphic serialization in the scope of 'Id' #406

Closed urosjarc closed 1 year ago

urosjarc commented 1 year ago

I use ...

dependencies {
    implementation("org.litote.kmongo:kmongo-id-serialization:4.8.0")
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:1.5.0")
}

And this code...

@Serializable
data class Test(
    @Contextual val _id: Id<Test> = newId(),
    val ime: String,
    val priimek: String,
)

fun main() {
    val json = Json {
        IdKotlinXSerializationModule
    }
    val test = Test(ime="asdf", priimek = "asdf")
    println(json.encodeToString(test))
}

Is giving me an error

Exception in thread "main" kotlinx.serialization.SerializationException: Class 'WrappedObjectId' is not registered for polymorphic serialization in the scope of 'Id'.
To be registered automatically, class 'WrappedObjectId' has to be '@Serializable', and the base class 'Id' has to be sealed and '@Serializable'.
Alternatively, register the serializer for 'WrappedObjectId' explicitly in a corresponding SerializersModule.
urosjarc commented 1 year ago

Oh I didn't see that you can serialize objects like this...

@Serializable
data class Test(
    @Contextual val _id: Id<Test> = newId(),
    val ime: String,
    val priimek: String,
)

fun main() {
    val test = Test(ime="asdf", priimek = "asdf")
    println(test.json)
}