https://kotlinlang.org logo
#serialization
Title
# serialization
b

bod

03/25/2023, 3:25 PM
Hello, World! I have a sealed class
Event
and am using
@JsonClassDiscriminator
successfully for its subtypes. But now I have one of the subtypes (
Message
) that should itself be a sealed class with a few sub-subtypes:
Copy code
┌─────┐
        │Event│  discriminator: "type"
        └──▲──┘
┌─────┐    │   ┌───────┐
│React├────┴───┤Message│  discriminator: "subtype"
└─────┘        └───▲───┘
          ┌───┐    │    ┌────┐
          │Add├────┴────┤Edit│
          └───┘         └────┘
Naturally I'd put another
@JsonClassDiscriminator
on
Message
but that's not allowed. Any tip on how I should handle this?
d

Dominaezzz

03/26/2023, 11:44 AM
Why is it not allowed?
b

bod

03/26/2023, 11:45 AM
I'm not sure what the reason is, but the doc says:
It is not possible to define different class discriminators for different parts of class hierarchy.
and if you actually try it in the IDE it will be red 🙂
d

Dominaezzz

03/26/2023, 11:48 AM
What happens if you ignore the IDE and run the code?
b

bod

03/26/2023, 11:49 AM
haven't tried to be honest...
but the documentation seems pretty clear about it
d

Dominaezzz

03/26/2023, 11:52 AM
Indeed. You might need to make
Message
a concrete class then, then have a polymorphic member.
b

bod

03/26/2023, 11:54 AM
I did something similar currently, but it's not very satisfactory - I'd love to have a class hierarchy that looks like the API one
d

Dominaezzz

03/26/2023, 11:58 AM
Though thinking about it, I suppose it'd be rather tricky to serialize something like this.
Copy code
val event: Event = Add()
Since there isn't a way to figure out the
Message
class in between.
You could consider using a single discriminator for the whole hierarchy.
b

bod

03/26/2023, 12:03 PM
You could consider using a single discriminator for the whole hierarchy.
Do you mean a change in the backend? (it's out of my hands, this is actually for the Slack API)
d

Dominaezzz

03/26/2023, 12:06 PM
I see. At this point your best best is to create an issue and/or custom serializer.
b

bod

03/26/2023, 12:08 PM
I saw a bunch of issues about the topic but not sure they were exactly like what I'm trying to do 🙂 I think I'll open one then. Thanks a lot for replying!
4 Views