03/01/2023, 10:22 AM
Hey, can you use a custom serializer for a specific format? I want to write one class and use it with different formats, like Json and my own format.
data class Foo(@MyFormat(Custom::class) val bar: Int)

object Custom: KSerializer<Int> { .. }
With Json, I want to use native integer handling:
{"bar": 42
}` but my format should produce
There is an option to use
but this only works only on a type, eg Int but you can't use different contextual serializers for the same type, eg Int.
data class Foo(@Contextual val bar: Int, @Contextual val other: Int)

object BarCustom: KSerializer<Int> { .. }
object OtherCustom: KSerializer<Int> { .. }

MyFormat(serializerModule = SerializersModule {
  contextual(Int::class, BarCustom)

Derek Ellis

03/01/2023, 12:04 PM
You could probably have a custom serializer that delegates to another encoder depending on the type of encoder that is being passed in? (i.e. checking if
encoder is JsonEncoder
and doing something different than if
encoder is MyFormatEncoder


03/01/2023, 1:32 PM
Okay, this would work but results writing a custom serializer for each class.