Does kotlinx serialization work with Java projects...
# serialization
d
Does kotlinx serialization work with Java projects, or is the Kotlin compiler required for
@Serializable
annotated classes?
j
Serialization is a Kotlin compiler plugin, and thus requires the Kotlin compiler.
You can still serialize Java types in your object graph though by manually writing a serializer for it
gratitude thank you 1
s
...or also look at some of the additional serializers that https://github.com/Kantis/ks3/blob/main/doc/jdk.md provides.
e
of course the easier option, if available, would be to convert the Java class to a Kotlin class and apply serialization to it the usual way
if you can modify the Java type, you could implement the serializer on the Java type itself in a way that the Kotlin serialization plugin would be happy to pick up, with code similar to what the serialization plugin itself would generate for Kotlin. but it's a pain and I wouldn't recommend it
if you can't modify the library that the class is in, you'll have to use an external serializer, e.g.
d
Oh thanks that is super useful… din’t know about the external serializer
e
external serializers require that use sites be annotated
Copy code
@Serializable
data class KData(val data: @Serializable(with = JDataSerializer::class) JData)
or contained within a file with
Copy code
@file:UseSerializers(JDataSerializer::class)
otherwise they won't be found though
gratitude thank you 1
(well it would also be possible to use contextual serialization,
Copy code
@Serializable
data class KData(val data: @Contextual JData)

val json = Json {
    serializersModule = SerializersModule {
        contextual(JDataSerializer)
    }
}

println(json.encodeToString(KData(JData(0, 1))))
but I don't think that's a better option)