How to use kotlinx.serialization from Java?

Hi,

I am trying to use Json.encodeToString with custom SerializersModule from Java class and I can not understand how to create Json instance and pass serializersModule as everything in API is private.

Json class is sealed with internal constructor.

Please assist how to do following code from Java:
var format = Json { serializersModule = someCustomModule }
format.encodeToString(someModel)

        var json = JsonKt.Json(Json.Default, b -> {
            b.setSerializersModule(...);
            return null;
        });

        json.encodeToString(...)
1 Like

Thanks @fvasco,

Json instance was created, but encodeToString is an inline function with reified T parameter which is not visible from Java.

How to property call encodeToString?

Are you considered to use the regular version?

json.encodeToString(SomeModel.serializer(), someModel)
2 Likes

@fvasco, thanks!
I almost reach the goal.

The only thing is in Java you need to use SomeModel.Companion.serializer() method.
I have tried to find serializer() before, but forgot about Companion as replacement of static methods.

But I still have one question - how to apply this approach to serialize SomeModel[] or List?
There is not possible to address serializer() in this situation.

I have made workaround adapter for Java on Kotlin. Is it a only way to add Array and List support?

class Serializer(val module: SerializersModule) {

    val stringFormat = Json { serializersModule = module }

    fun toJson(value: Any): String {
        val serializer = serializer(value.javaClass)
        return stringFormat.encodeToString(serializer, value)
    }

    fun <T> fromJson(json: String, targetClass: Class<T>): T {
        @Suppress("UNCHECKED_CAST")
        val deserializer = serializer(targetClass) as KSerializer<T>
        return stringFormat.decodeFromString(deserializer, json)
    }

} 

Take a look to kotlinx.serialization.builtins.BuiltinSerializersKt.ListSerializer

2 Likes

Bingo!!! Thank you very much! You made my day!