Search code examples
mongodbkotlinserialization

Kotlin - How to add serializer to MongoDB


How to add a serializer for @Contextual annotated types in Kotlin Coroutine Driver?

I have code as follows:

@Serializable
data class D(@Contextual val d: LocalDate)

fun main() {
    val d = D(LocalDate.now())
    val json = Json {
        serializersModule += SerializersModule {
            contextual(LocalDateSerializer)
        }
    }
    println(json.encodeToString(d)) // {"d":"2024-04-09"}

    val client = MongoClient.create(url)
    val test = client.getDatabase("web-im")
        .getCollection<D>("test")

    runBlocking {
        test.insertOne(d) // Error
    }
}

And I got error:

Exception in thread "main" kotlinx.serialization.SerializationException: Serializer for class 'LocalDate' is not found.
Please ensure that class is marked as '@Serializable' and that the serialization compiler plugin is applied.

Can I add my LocalDateSerializer to serializersModule that the MongoDB uses?


Solution

  • I found it, use KotlinSerializerCodecProvider:

    @Serializable
    data class D(@Contextual val d: LocalDate)
    
    fun main() {
        val d = D(LocalDate.now())
        val client = MongoClient.create(url)
        val kotlinProvider = KotlinSerializerCodecProvider(
            SerializersModule { contextual(LocalDateSerializer) }
        )
        val test = client.getDatabase("web-im")
            .withCodecRegistry(
                CodecRegistries.fromRegistries(
                    CodecRegistries.fromProviders(kotlinProvider)
                )
            )
            .getCollection<D>("test")
    
        runBlocking {
            test.insertOne(d)
        }
    }