1. Introduction
When you’re just starting to work with JSON, you want to believe a simple fairy tale: “JSON always matches my model.” It’s a great fairy tale as long as you write the format yourself or you have a strict contract, and nobody sends you an “id”: "10" instead of 10. But as soon as the format becomes “no schema,” “version drifts,” “fields are sometimes missing,” you either start multiplying dozens of nullable fields, or you start catching decoding errors, or you pretend it’s not your problem (spoiler: it will be).
JsonElement is a different approach: we don’t try to immediately turn the input into a strict Kotlin model. Instead, we first turn JSON into a tree. And only then do we decide what we need from that tree, and how to live with it next.
Officially, JsonElement is a sealed class representing a single JSON element, and it can be a primitive, an array, or an object. At the same time, toString() prints the tree back as valid JSON. (kotlinlang.org)
2. JSON as a tree: the DOM idea without HTML
If you’ve ever seen the DOM in a browser, the idea will be familiar: a document (or data) is a tree of nodes. Nodes have a type, and different types have different “insides.” An object has fields by keys, an array has elements by indices, and a primitive has a value.
It’s important to get used to the idea: in JSON there is no guarantee that the root is an object. The root can be an array ([ ... ]), a number (123), a string ("ok"), a boolean (true), or null. So the basic reflex “I’ll just cast it to JsonObject right away” is like going outside without an umbrella because “the sky looks fine.” Sometimes it works. Sometimes you get soaked.
A small diagram of how we’re going to think about it:
flowchart TD
A["JSON text (String)"] --> B["Json.parseToJsonElement(...)"]
B --> C["JsonElement (root)"]
C --> D{"What node type is it?"}
D -->|JsonObject| E["Fields: key -> JsonElement"]
D -->|JsonArray| F["Elements: [JsonElement]"]
D -->|JsonPrimitive| G["Value (as a primitive)"]
D -->|JsonNull| H["Explicit null value"]
3. Node types in the JsonElement tree
To walk the tree confidently, you need to know the “species of trees.” In kotlinx.serialization, the JSON tree has several main types.
According to the docs, JsonElement can be JsonPrimitive, JsonArray, or JsonObject.
Separately, there is JsonNull—a singleton object (object) representing JSON null.
Let’s put this into a table so your brain stops panicking:
| Node type | Example in JSON | How to think about it | What it resembles |
|---|---|---|---|
|
|
“dictionary/map of fields” | |
|
|
“list of elements” | |
|
|
“a single value” | a container for primitives |
|
|
“null as a node” | a singleton object |
Pay attention to a small psychological trap: JsonNull is not the absence of a field. It is exactly the value null that is explicitly present in JSON. We’ll talk about the difference separately a bit later.
4. Parsing a string into a tree: Json.parseToJsonElement(...)
Now comes the moment of “it was complicated, and now it’s one line.” To turn JSON text into a tree, we use:
- Json.parseToJsonElement(string: String): JsonElement
The documentation says it directly: the function deserializes a JSON string into the corresponding JsonElement representation and throws SerializationException if the string is not valid JSON.
A minimal example—maximally short and honest:
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
fun main() {
val text = """{"id": 10, "name": "Alice"}"""
val root: JsonElement = Json.parseToJsonElement(text)
println(root) // {"id":10,"name":"Alice"}
}
Notice an important thing: we do not use @Serializable and decodeFromString. We simply build a tree.
If you read JSON from “outside” (a file, user input, someone else’s API), it’s better to immediately get used to try/catch, because the input may be not JSON, but “almost JSON” (a separate art genre).
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
fun tryParseJson(text: String): JsonElement? {
return try {
Json.parseToJsonElement(text)
} catch (e: SerializationException) {
null
}
}
5. Basic navigation through the JsonElement tree
When you navigate JsonElement, you keep doing the same thing: assume a node type, check it, then move on. So it’s convenient to have a small function that can at least describe what we’re looking at.
Checking a node type with when
A when by node type is basically a flashlight in a dark forest:
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
fun describe(el: JsonElement): String = when (el) {
is JsonObject -> "object(fields=${el.size})"
is JsonArray -> "array(items=${el.size})"
is JsonPrimitive -> "primitive"
is JsonNull -> "null"
}
There’s a subtle detail here: JsonNull is technically a JsonPrimitive (in the hierarchy it’s a descendant of the primitive), so in real code you’ll often distinguish these cases more carefully. But as a starter map of the terrain—it works.
Navigation: object → field → array → elements
Now let’s show navigation “object → field → array → elements.” We do it as straightforwardly as possible, but already with safe casts as?:
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
fun main() {
val root = Json.parseToJsonElement("""{"tags":["kotlin","json"]}""")
val obj = root as? JsonObject ?: return
val tags = obj["tags"] as? JsonArray ?: return
for (tagEl in tags) {
val tag = (tagEl as? JsonPrimitive)?.content
println(tag) // kotlin then json
}
}
This isn’t “pretty” code yet, but it’s very instructional: each step explicitly shows where we can be wrong about the type. In the next lecture we’ll turn chunks like this into neat helper functions, so we don’t write the same thing 200 times (because that’s usually how burnout starts).
Why does JsonObject["key"] return JsonElement?
When you take a field from a JsonObject, you write something like obj["name"]. And here the interesting part begins: the result is nullable. And that’s not trolling—it’s the correct model of reality.
The reason is simple: the field may be missing. And a missing field is not the same as a field with the value null.
Let’s show it with an example. We have two JSONs:
1) The field is not present at all: {}
2) The field is present but equals null: {"nickname": null}
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
fun main() {
val obj1 = Json.parseToJsonElement("""{}""") as JsonObject
val obj2 = Json.parseToJsonElement("""{"nickname": null}""") as JsonObject
val a = obj1["nickname"]
val b = obj2["nickname"]
println(a == null) // true (field is missing)
println(b is JsonNull) // true (field exists, but value = null)
}
It’s important to keep this difference in mind, because later (in validation and in “safe extraction”) you’ll make decisions like: “if the field is missing—it’s an error,” “if the field exists and is null—allow it,” “if the field is a string—OK, if it’s an array—complain.”
Today our goal is simpler: learn to see these cases and not mix them up.
How to read a tree “in depth” without turning your code into mush
At this stage it’s very easy to make the code unreadable. Beginners often write: “chain everything immediately, without pauses.” As a result you get something like obj["x"]!!.jsonObject["y"]!!.jsonArray[0]..., and it crashes at the first structural deviation.
Today we’re not building perfect helper functions yet (that’s the next lecture), but we can adopt a basic style that already makes code calmer: move in small steps and give variables normal names.
Here’s an example of “get the items array from an object”—no fanaticism, but readable:
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
fun getItemsArray(rootObj: JsonObject): JsonArray? {
val itemsEl = rootObj["items"] ?: return null
return itemsEl as? JsonArray
}
At this point many people ask: “why not as JsonArray?” Because right now we’re working with a dynamic structure. And if we got it wrong—let it be null, not a crash. And how exactly to react to null is a higher-level decision (and it will appear in the lecture about safe extraction and validation).
6. The JSON root doesn’t have to be an object
At the habit level, it’s very important to stop thinking: “root = object.” In the JSON world, it doesn’t have to be that way. And if you write code that crashes on "[" as the first character, then congratulations: your parser lives in a world of strict moral principles, but the data does not.
Let’s look at three root variants.
Root is an array
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
fun main() {
val root = Json.parseToJsonElement("""[1, 2, 3]""")
val arr = root as? JsonArray ?: return
println(arr.size) // 3
}
Root is a primitive
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonPrimitive
fun main() {
val root = Json.parseToJsonElement("42")
val p = root as? JsonPrimitive ?: return
println(p.content) // 42
}
Root is null
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonNull
fun main() {
val root = Json.parseToJsonElement("null")
println(root is JsonNull) // true
}
Yes, JSON can be just null. And sometimes it’s even a “valid contract” (although it sounds like a meme).
7. A mini JSON inspector for a console app
To avoid leaving the knowledge in a vacuum, let’s add a small debugger feature to our learning console app. Let me remind you of the overall course storyline: we already stored data in JSON, but there the format was stable and we decoded into models. Now we’ll add a mode that takes JSON text and says: “what is this structurally, anyway?”
This is not “full processing,” but an inspector. It helps when your file/input doesn’t match expectations and you want to quickly understand where reality broke.
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
fun inspectJson(text: String): String {
val root: JsonElement = try {
Json.parseToJsonElement(text)
} catch (e: SerializationException) {
return "This is not JSON"
}
return when (root) {
is JsonObject -> "Root: object, fields=${root.size}"
is JsonArray -> "Root: array, elements=${root.size}"
is JsonPrimitive -> "Root: primitive (${root.content})"
is JsonNull -> "Root: null"
}
}
And a tiny main to see it live:
fun main() {
val text = readln()
println(inspectJson(text))
// Input example: {"id":1,"name":"Ann"}
// Output: Root: object, fields=2
}
Yes, it looks simple. But it’s exactly these “simple things” that later save hours of debugging: at least you understand what you’re parsing and why your code that expects an object got an array.
8. Common mistakes when getting to know JsonElement
Mistake #1: assuming the JSON root is always an object.
This is the most common trap, because most “nice” JSON examples on the internet start with {...}. In practice, the root can be an array, a primitive, or null, and JsonElement exists precisely so you don’t make false assumptions. Check the root type explicitly, especially where JSON comes from outside.
Mistake #2: doing forced casts as JsonObject without checks.
A forced cast is a bet: “I’m 100% sure.” With unstable JSON it’s almost always a bet against yourself. It’s much safer to start with as? and early exit (return) while you’re building an understanding of the structure. And only later, when you add a validation layer, you can make stricter decisions.
Mistake #3: confusing a missing field with a field whose value is null.
obj["key"] returns null if the field is missing, but if the field exists and equals JSON null, you get JsonNull. These two cases often mean different things for business logic: “they didn’t send it” and “they sent it, but it’s empty” are not the same.
Mistake #4: thinking that parseToJsonElement is “safe and never crashes.”
Parsing fails on invalid JSON and throws SerializationException. That’s normal, honest, and needs to be handled. Especially if you let users type JSON by hand (people can type, but sometimes they add an extra comma out of pure love for art).
Mistake #5: trying to “do everything at once” in a single function.
Beginners often mix parsing, navigation, extraction, defaults, range checks, and error printing into one huge block. You end up with code that’s impossible to maintain. Today we intentionally limited ourselves to the first step: we represented JSON as a tree and learned basic navigation. Next will be safe extraction and a separate validation layer—and that’s where a neat architecture will appear.
GO TO FULL VERSION