05/24/2023, 6:45 PM
Any ideas on how to write a custom JsonSerializer for a sealed class?
let's take a very simple sealed class
sealed class Parent {
  data class Child1(val name: String): Parent()
  data class Child2(val name: String): Parent()
I created a serializer like this:
class ParentSerializer : JsonSerializer<Parent> {
  companion object {
    const val CLASSNAME = "CLASSNAME"
    const val DATA  = "DATA"

  override fun serialize(
      src: Parent,
      typeOfSrc: Type,
      context: JsonSerializationContext
  ): JsonElement {
    val jsonObject = JsonObject()
    jsonObject.add(DATA, context.serialize(src))
    return jsonObject
and using it like this:
val gson = GsonBuilder()
        .registerTypeAdapter(, ParentSerializer())
But when I try to use this
gson.toJson(listOf(Parent.Child1("first"), Parent.Child2("second")))
it's not calling the serialize method