← Back to garden 🤏

output

Kotlin Serialization: Deserialize without schema


Description

When working with JSON objects it is common to use @Serializable data classes, but sometimes, you might want to quickly experiment or your data structure might not be consistant, you can use parse the JSON string into a JsonElement which in turn can be:

  • A nested object
  • A primitive value
  • An Array
Json.parseToJsonElement(YourJsonString) // Create JSONElement
	.jsonObject.toMap() // Object as a Map
	.jsonPrimitive.content // OR Access property
	.jsonArray // OR Access Array


Construct a JSON object programatically

Kotlinx Serialization provides a DSL to build a JsonElement

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