I have two Kotlin data classes, Song
and Thumbnail
, and I am facing a lot of nesting that I want to avoid. Here are the class definitions:
data class Song(
val title: String,
val year: Int,
val watchId: String,
val thumbnails: List<Thumbnail>
)
data class Thumbnail(
val url: String,
val width: Int,
val height: Int
)
I also have JSON data that I need to parse:
{
"search": {
"result": [
{
"title": "Only Time",
"year": 2000,
"watchId": "ifgihvidvcs",
"thumbnails": [{"width": 60, "height": 60, "url": "url"}]
}
],
// some data I don't need now here
}
// and here
}
I've read the Kotlin Serialization Guide, but the only way I see to handle this nesting is to write surrogate classes and use their descriptors. Is there a way I can write a composite descriptor without writing surrogate classes?
Two ways: you can either first deserialize to a JsonObject, and then deserialize the result array accordingly again. Another method might be to use a transforming serializer (https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-transforming-serializer/). That way, you can make sure the useless data is "unwrapped" (just like in the example in the documentation) before the content is deserialized. If this does not give the desired result, you can always just write your own serializer.