https://kotlinlang.org logo
#ktor
Title
# ktor
i

Ivan Brko

05/07/2020, 12:51 PM
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

Ivan Brko

05/07/2020, 12:57 PM
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

David Eriksson

05/07/2020, 12:57 PM
Maybe I misinterpreted your question 😉
i

Ivan Brko

05/07/2020, 12:59 PM
Sorry, accidentally sent unfinished message above, so I edited it.
d

David Eriksson

05/07/2020, 1:04 PM
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

Ivan Brko

05/07/2020, 1:08 PM
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

David Eriksson

05/07/2020, 1:12 PM
Can't say for sure sorry
i

Ivan Brko

05/07/2020, 1:12 PM
Ok, great. Thanks for the help!
d

David Eriksson

05/07/2020, 1:12 PM
But the @Serializable annotations should be picked up by the compiler plugin
i

Ivan Brko

05/07/2020, 1:13 PM
Yes, but the problem is when I can't annotate the data class as it is not in my code.
d

David Eriksson

05/07/2020, 1:30 PM
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 {}