Home > Software design >  Kotlin - What is the easiest way to create a generic data object to transform into JSON for API requ
Kotlin - What is the easiest way to create a generic data object to transform into JSON for API requ

Time:07-22

It is very easy to create native generic objects that can be serialized into JSON in dynamically typed languages like Python, PHP, or JS.

With Kotlin, it seems like I will need to define a serializable data class, at the very least, in order to be able to compose JSON for transmission. This is workable, but it breaks down pretty quickly when the data is complex or variable, and because of this is not very reusable.

Is there a good approach (using Kotlin) that allows for similar behavior to the dynamic approach?

I think ultimately, I'm looking for a generic object type, where I can assign properties, both flat and nested, which can then be serialized using the kotlinx serialization package - does anything like this exist with Kotlin?

CodePudding user response:

With Kotlinx Serialization, you can use Json element builders. They let you build JsonElement instances, which I think is the generic object you're looking for.

The example from the doc:

fun main() {
    val element = buildJsonObject {
        put("name", "kotlinx.serialization")
        putJsonObject("owner") {
            put("name", "kotlin")
        }
        putJsonArray("forks") {
            addJsonObject {
                put("votes", 42)
            }
            addJsonObject {
                put("votes", 9000)
            }
        }
    }
    println(element)
}

That being said, I would still advise using properly typed data classes instead, especially if you use this data in more places than just the place where you serialize JSON.

This is workable, but it breaks down pretty quickly when the data is complex or variable, and because of this is not very reusable

On the contrary, I would argue that when the data is complex, you want to let the compiler make sure your types are correct, instead of relying on arbitrary strings and typo-sensitive dynamic code.

  • Related