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)
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)
}
}