How can I define contextual JSON keys in kotlinx.serialization?

Hey there.

I’m trying to write a system for a thing in a game that is based around JSON, but I’m a little bit stuck on what to do at this point. I need to serialise

class ClickEvent(
    val action: ClickAction,
    val content: String
)

into a JSON string that looks something like this: "clickEvent": {"action": "content"} (where action is the click action enum’s name in lower case, e.g. ClickAction.OPEN_URL becomes “open_url”, and content is the string content from ClickEvent)
Every example of descriptors I can find online seems to assume that the descriptor must be static.

I’ve looked around quite a few places, but can’t seem to find anything on this. Is this even possible? If so, how?

1 Like

Hmmm, as a temporary workaround you can define classes that represent that data in the JSON way, i.e. like this:

sealed class ClickEventWithAction
class ClickEventOpenUrl(val open_url: String): ClickEventWithAction
class ClickEventCloseUrl(val close_url: String): ClickEventWithAction
// Etc
// you can also make this a function instead, but IMO the extension property looks nicer
val ClickEvent.withAction: ClickEventWithAction get() = when(action) {
    ClickAction.OPEN_URL -> ClickEventOpenUrl(content)
    ClickAction.CLOSE_URL -> ClickEventCloseUrl(content)
    // Etc
}

Yeah that’ll work, thanks!

1 Like