Andrew K
06/06/2023, 3:10 PMAndrew K
06/07/2023, 1:43 PMinterface 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")
}