--

You can definitely do something similar with Kotlin serialization. First, you don't need to use the object mapper all the way, you can also decode a String to JsonElement tree:

val data = Json.parseToJsonElement(str) as JsonObject

val className = (data["class"] as JsonPrimitive).content

val value = data["value"]!!

Then, just like Moshi, you can retrieve a serializer for a class name, as long as you annotate each supported class with @Serializable:

val serializer = serializer(Class.forName(className))

val response = Json.decodeFromJsonElement(serializer, value)

--

--

Christophe Beyls
Christophe Beyls

Written by Christophe Beyls

Android developer from Belgium, blogging about advanced programming topics.

Responses (1)