https://kotlinlang.org logo
Title
h

hfhbd

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.
@Serializable
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
4242
.
There is an option to use
@Contextual
but this only works only on a type, eg Int but you can't use different contextual serializers for the same type, eg Int.
@Serializable
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)
}
d

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

hfhbd

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