I have this serializer class that eases usage with...
# serialization
z
I have this serializer class that eases usage with the API im working with
Copy code
abstract class SingletonMapPolymorphicSerializer<T : Any>(
    tSerializer: KSerializer<T>,
    private val discriminator: String = tSerializer.descriptor.annotations.firstNotNullOfOrNull { it as? JsonClassDiscriminator? }?.discriminator ?: "type"
) : JsonTransformingSerializer<T>(tSerializer) {
    final override fun transformDeserialize(element: JsonElement) = buildJsonObject {
        val (type, value) = element.jsonObject.entries.single()

        put(discriminator, type)

        value.jsonObject.forEach { (k, v) -> put(k, v) }
    }

    final override fun transformSerialize(element: JsonElement) = buildJsonObject {
        putJsonObject(element.jsonObject.getValue(discriminator).jsonPrimitive.content) {
            element.jsonObject.forEach { (k, v) -> if (k != discriminator) put(k, v) }
        }
    }
}
Copy code
@Serializable
sealed interface Example {
    object Serializer : SingletonMapPolymorphicSerializer<Example>(serializer())
}

class ExampleBody {
  val example: @Serializable(Example.Serializer::class) Example
}
Is there anyway to remove the need for having to declare a Serializer object within the class? Ideally I should be able to just annotate the
Example
interface with the serializable annotation and it would work
e
if that's how polymorphism works everywhere in your API, perhaps you should use a custom format instead of having custom serializers everywhere
(very unimaginatively named and barely tested but) if I understand correctly, this would behave the way you want, using the default plugin-generated serializers