Asked i serialization channel, nobody replied, may...
# ktor
i
Asked i serialization channel, nobody replied, maybe someone knows here: Does anyone know if I can somehow register a serializer in ktor (using kotlinx.serialization)? I am writing a Ktor sever and I need to return a data class from a 3rd party library, so I can't annotate it with @Serializable. I can write a serializer for it, but how to tell Ktor to use this serializer?
i
Thanks for the answer. Maybe I'm missing something obvious here but all I can see here is call to register method. If I'm using kotlinx.serialization isn't that handled internally when I call json()?
d
Maybe I misinterpreted your question 😉
i
Sorry, accidentally sent unfinished message above, so I edited it.
d
Copy code
application.install(ContentNegotiation) {
            register(ContentType.Application.Json, SerializationConverter())
        }

        application.routing {
            val model = MyEntity(
                777, "Cargo",
                listOf(
                    ChildEntity("Qube", 1),
                    ChildEntity("Sphere", 2),
                    ChildEntity(uc, 3)
                )
            )

            get("/") {
                call.respond(model)
            }'
But yes, MyEntity and ChildEntity have @Serializable
"External serializers for library classes"
i
Thanks. I know how to write my own serializer, I just don't know how to register that KSerializer in Ktor, so that it uses it when it is trying to serialize or deserialize data in API. For example, when using KMongo with kotlinx.serialization there is a method registerSerializer where I can register any non existing serializer.
👍 1
I'll check the samples you gave above in more detail, but I have to admit I still don't understand what will hapen when I write something like this:
Copy code
install(ContentNegotiation) {
    json()
    register(ContentType.Application.Json, SerializationConverter())
}
Both json() and I call register directly here for Json content. That is OK with Ktor?
d
Can't say for sure sorry
i
Ok, great. Thanks for the help!
d
But the @Serializable annotations should be picked up by the compiler plugin
i
Yes, but the problem is when I can't annotate the data class as it is not in my code.
d
Copy code
// Imagine that MyData is a third-party library class.
// Plugin will try to automatically serialize all constructor properties
// and public vars.
@Serializer(forClass = MyData::class)
object DataSerializer {}