'Polymorphic custom serialization strategy?

I'm having a really difficult time working this out. I have a polymorphic JSON structure that I want to parse and flatten. Basically this:

{
  "objectType": "type",
  "data": {...}
}

And the data object changes depending on type. What I would like to achieve is have a possibility to parse this json directly into a structure which only contains fields in data object. Preferably it should work on polymorphic principle like this:


@Serializable
@JsonClassDiscriminator("type")
abstract class Thing(val type: String)

@Serializable
@SerialName("image")
data class Image(val url: String, val width: Int, val height: Int): Thing("image")

val string = """
{
  "type": "image",
  "data": {
    "url": "..",
    "width": 140,
    "height": 250
  }
}
"""

println(Json.decodeFromString<Image>(string)))

I know it can be easily done by unwrapping manually but the api I'm interacting with has every single type (hundreds of them) inheriting from that Thing type and unwrapping it manually each time and writing separate implementation for all of them seems tedious and I would rather spent a week trying to figure out a generic solution for all.

The easiest way would be to implement a custom serializer for Thing like in this article but it must be terribly outdated cause I couldn't get that approach to work.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source