I have a JSON string to parse in which an element’s type can change from Object to an Array or can be Object.
How do we deal with this changing data type when creating a @Serializable data class in kotlin? In my example JSON string below, the “work” key can change between object or an array.
In a dynamic language like python, I would decode the JSON string and check it’s data type before using it. Is something like this possible in Kotlin with kotlinx.serialization.json library?
@Serializable
data class Work(
var company: String? = null,
var joining_date: Int? = null
)
@Serializable
data class Data(
var name: String? = null,
var fullname: String? = null,
var age: Int? = null,
var weight: Double? = null,
var hobbies: List<String>? = null,
var work: Work? = null
)
val json = Json.decodeFromString<Data>(json_str)
For dynamic schemas we can always deserialize to JsonObject or create custom serializers. But it’s best to avoid such flexible schemas in the first place - no matter the language we use.
Based on your description I suspect that you probably want to implement a custom polymorphic deserializer, but could you first provide a more complete example?