https://kotlinlang.org logo
#serialization
Title
# serialization
y

Yuri

03/06/2024, 4:05 PM
Hello, I need to write custom serializer for my type, which delegates most of serialization logic to generated basic serializer.
Copy code
@Serializable 
data class Xxx(...)

object XxxSerializer : KSerializer<Xxx> {
    private val delegate = Xxx.serializer()
... custom serialize/deserialize logic using delegate
}

val json = Json {
serializersModule = SerializersModule { contextual(Xxx::class, XxxSerializer) }
}
json instance is being used for Retrofit converter factory which performs deserialization with
json.serializersModule.serializer(type)
. This code picks default serializer instead of custom one, because
Xxx
has
@Serializable
annotation. Is it possible to force runtime to use contextual serializer for this class? Seems like
@UseContextualSerialization
should help, but I couldn't figure out correct syntax.