I'm developing a hierarchy for polymorphic seriali...
# serialization
c
I'm developing a hierarchy for polymorphic serialization using Kotlin. I have a sealed interface for the polymorphic type, with some concrete cases as data classes identified using @SerialName annotations. I would like to have one of these cases be the default, and in that case the type field should not be serialised, i.e. elements with a null type should be considered to be that default case. Is this possible? I only need JSON serialisation on the JVM.
I ended up using
JsonTransformingSerializer
for this:
Copy code
open class NoDefaultDiscriminatorSerializer<T : Any>(base: KSerializer<T>): JsonTransformingSerializer<T>(base) {
  override fun transformDeserialize(element: JsonElement): JsonElement {
    return if (element.jsonObject["type"] == null) {
      JsonObject(element.jsonObject + Pair("type", JsonPrimitive("custom")))
    } else element
  }

  override fun transformSerialize(element: JsonElement): JsonElement {
    return if (element.jsonObject["type"]?.jsonPrimitive?.content == "custom") {
      JsonObject(element.jsonObject.filterKeys { it != "type" })
    } else element
  }
}