Thread
#serialization
    phldavies

    phldavies

    9 months ago
    Is there any way to tell kotlinx.serialization that the class-discriminator for a polymorphic field is defined by a sibling field? i.e.
    {"eventType": "MyEventType": "event": { … /*MyEventType fields */ }
    or will we need a custom serializer for this?
    Dominaezzz

    Dominaezzz

    9 months ago
    Yes that's how polymorphism current works.
    phldavies

    phldavies

    9 months ago
    I understood the current polymophism to embed the class-discriminator into the object itself, i.e.:
    @Serializable sealed class EventBase
    @Serializable @SerialName("greet") data class GreetEvent(val name: String) : EventBase()
    @Serializable data class EventPayload(val event: EventBase)
    fun main() = println(Json.encodeToString(EventPayload(GreetEvent("Bob"))))
    results in
    {
      "event": {
        "type": "greet",
        "name": "Bob"
      }
    }
    but the existing model is declared as
    {
      "eventType": "greet",
      "event": {
        "name": "Bob"
      }
    }
    Dominaezzz

    Dominaezzz

    9 months ago
    Ah I see. You'll need a greet event and a greet event payload then.
    phldavies

    phldavies

    9 months ago
    Yeah I’ve played with that approach and it seems to work for the most part, but makes for a lot of noise and duplication given our EventPayload has 4 fields, and all four would need to be abstract at the root of the hierarchy and defined on each data class leaf. I have managed to achieve something with a custom serializer but I needed to cast the root event serializer as the internal SealedClassSerializer in order to lookup the serializers by type/serialName which I’m not happy with either
    Dominaezzz

    Dominaezzz

    9 months ago
    I currently have this duplication issue and I don't even have the nesting you do. I don't mind it too much but I guess that's subjective.