spand
09/14/2023, 7:47 AMSerializersModule
that can serialize any implementation of a generic interface. I have it working by marking the value @Contextual
but I would really prefer not to have to mark them all as such and only rely on a configuration in the SerializersModule
. Example code in thread 🧵spand
09/14/2023, 7:48 AM@Test
fun boxCanBeSerialized() {
val jsonStr = jsonFormat.encodeToString(TestObject(DefaultBox("test")))
assertEquals("""{"box":{"t":"test"}}""", jsonStr)
}
val jsonFormat = Json {
prettyPrint = false
serializersModule = SerializersModule {
contextual(Box::class) {
DefaultBoxSerializer(it[0])
}
}
}
interface Box<T> {
fun get(): T
}
@Serializable
class DefaultBox<T>(private val t: T) : Box<T> {
override fun get(): T = t
}
class DefaultBoxSerializer<R, T : Box<R>>(
rSerializer: KSerializer<R>,
) : KSerializer<T> {
private val impl = DefaultBox.serializer(rSerializer)
override val descriptor: SerialDescriptor
get() = impl.descriptor
override fun deserialize(decoder: Decoder): T {
TODO("Not yet implemented")
}
override fun serialize(encoder: Encoder, value: T) {
encoder.encodeSerializableValue(impl, DefaultBox(value.get()))
}
}
@Serializable
class TestObject<T>(
@Contextual // <-- How do I get rid of this ?
val box: Box<T>,
)
glureau
09/14/2023, 10:14 AMval jsonFormat = Json {
prettyPrint = false
serializersModule = SerializersModule {
polymorphic(Box::class) {
subclass(DefaultBox::class)
}
}
}
spand
09/14/2023, 10:15 AMglureau
09/14/2023, 10:15 AMcontextual
allows to setup a custom serializer for a given class
polymorphic
is used to describe subclasses of an interfaceglureau
09/14/2023, 10:15 AMspand
09/14/2023, 10:15 AMglureau
09/14/2023, 10:16 AMspand
09/14/2023, 10:20 AMpolymorphicDefaultSerializer
except it doesnt provide the generic type `KSerializer`s that contextual doesspand
09/14/2023, 10:22 AM