Replace Jackson with kotlinx.serialization in Javalin framework

1.2k views Asked by At

I'm trying to replace the default Javalin JSON serializer Jackson by Kotlinx.serialization.

The documentation show how to do it with GSON serializer.
Unfortunately kotlinx serializer has a different function signature and I can't figure out how to pass arguments through.

Serialization is OK but deserialization with decodeFromString function require to be passed a type given by the mapping function as targetClass.

I'm stuck here:

val kotlinx = Json { coerceInputValues = true }
    
JavalinJson.toJsonMapper = object : ToJsonMapper {
    override fun map(obj: Any): String = kotlinx.encodeToString(obj)
}
    
JavalinJson.fromJsonMapper = object : FromJsonMapper {
    override fun <T> map(json: String, targetClass: Class<T>): T = kotlinx.decodeFromString(json)
}

But I get: Cannot use 'T' as reified type parameter. Use a class instead.

I also tried:

JavalinJson.fromJsonMapper = object : FromJsonMapper {
    override inline fun <reified T> map(json: String, targetClass: Class<T>): T = kotlinx.decodeFromString(json)
}

But I get a warning: Override by an inline function and an error: Override by a function with reified type parameter.

I'm new to kotlin and I'm struggling understanding what's wrong with this override.

1

There are 1 answers

9
Михаил Нафталь On BEST ANSWER

Try this one:

JavalinJson.toJsonMapper = object : ToJsonMapper {
    override fun map(obj: Any): String {
        val serializer = serializer(obj.javaClass)
        return kotlinx.encodeToString(serializer, obj)
    }
}

JavalinJson.fromJsonMapper = object : FromJsonMapper {
    override fun <T> map(json: String, targetClass: Class<T>): T {
        @Suppress("UNCHECKED_CAST")
        val deserializer = serializer(targetClass) as KSerializer<T>
        return kotlinx.decodeFromString(deserializer, json)
    }
}