I'm trying to use generics with polymorphism with ...
# serialization
a
I'm trying to use generics with polymorphism with kotlin serialization. I'm able to get this example code to work: https://github.com/Kotlin/kotlinx.serialization/blob/master/guide/example/example-poly-17.kt. But the third party endpoint I'm trying to deserialize has the type outside of the generic class. I'm not sure how to set that up.
Not sure if its the best solution, but this seems to work:
Copy code
interface MyInterface

@Serializable
data class MyClass(
    val myString: String,
) : MyInterface

@Serializable
data class MyData<T: MyInterface>(
    @SerialName("type") val type: String,
    @SerialName("data") val data: T,
)

val jsonString = "{type: \"myType\", data: {myString: \"myString\"}}"
val json = Json {}
val jsonObject = json.decodeFromString<JsonObject>(jsonString)

val type = jsonObject["type"]?.jsonPrimitive?.content
val myObject = when (type) {
    "myType" -> json.decodeFromString<MyData<MyClass>>(jsonString)
    else -> throw SerializationException("Unknown message type: $type")
}
155 Views