CLOVIS
11/11/2025, 9:34 PM@Serializable(with = ObjectId.Serializer::class)
class ObjectId : Comparable<ObjectId> {
…
class Serializer : KSerializer<ObjectId> {
override val descriptor: SerialDescriptor
get() = PrimitiveSerialDescriptor("opensavvy.ktmongo.bson.types.ObjectId", PrimitiveKind.STRING)
@LowLevelApi
override fun serialize(encoder: Encoder, value: ObjectId) {
encoder.encodeString(value.hex)
}
override fun deserialize(decoder: Decoder): ObjectId =
decoder.decodeString().let(::ObjectId)
}
}
and the code (in another module):
val decoder = BsonDecoder(EmptySerializersModule(), this)
return decoder.decodeSerializableValue(serializer(type) as KSerializer<T?>)
where BsonDecoder : kotlinx.serialization.encoding.Decoder , but on non-JVM platforms I get:
kotlinx.serialization.SerializationException: Serializer for class 'ObjectId' is not found.
Please ensure that class is marked as '@Serializable' and that the serialization compiler plugin is applied.
To get enum serializer on Kotlin/Native, it should be annotated with @Serializable annotation.
To get interface serializer on Kotlin/Native, use PolymorphicSerializer() constructor function.
The serialization plugin is applied to both modules.
I see I can explicitly specify it with:
val module = SerializersModule {
contextual(ObjectId::class, ObjectId.Serializer())
}
val decoder = BsonDecoder(module, this)
return decoder.decodeSerializableValue(module.serializer(type) as KSerializer<T?>)
(even though the type is NOT used with @Contextual)—won't this mean that this code will break with user-provided types, though? I can't hardcode all the serializers that exist.efemoney
11/12/2025, 4:53 PMSerializersModule . Also on non-JVM platforms it seems you cannot use reflection to find serializers so you need to register your serializersefemoney
11/12/2025, 4:54 PMCLOVIS
11/12/2025, 7:12 PMCLOVIS
11/12/2025, 7:12 PMefemoney
11/12/2025, 7:14 PMjoseph_ivie
11/12/2025, 7:20 PMObjectId type? What if you're accidentally using the MongoDB declared one instead of the one you declared?CLOVIS
11/12/2025, 7:23 PM:bson-multiplatform module, which doesn't have a dependency on the MongoDB one, so it shouldn't be possible that it's confusing themCLOVIS
11/12/2025, 7:31 PMjoseph_ivie
11/12/2025, 7:46 PMKType for this, not reification - I didn't notice that. I haven't tried KType usage.CLOVIS
11/12/2025, 7:47 PMKType , then serializer(t) to get the serializer. I'm doing this to avoid having a serializer in the public API of the main module, since the other implementation doesn't use KotlinX.Serialization.joseph_ivie
11/12/2025, 7:48 PMCLOVIS
11/12/2025, 7:49 PMCLOVIS
11/12/2025, 7:53 PMSerializerModule and tell the plugin "hey, put all the serializers in you can find in there"?