Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 134 ยท Text, Files and Time

Working with JSON Text

Learn how to build, escape and parse JSON text in plain Kotlin - buildString, string escaping, a small recursive parser, sealed JSON values - and when to reach for kotlinx.serialization instead.

JSON is the language that programs use to talk to each other: web APIs, config files, logs and message queues all speak it. A JSON document is plain text built from only a few pieces: objects ({"name": "Ada"}), arrays ([1, 2, 3]), strings, numbers, true, false and null. Because the format is so small, it is a great exercise to handle it by hand, and doing so teaches you exactly what a JSON library does for you.

In production you will almost always use a library. The standard choice for Kotlin is kotlinx.serialization, which is not available in our in-browser runner, so we show it as a read-only example. Everything else in this lesson runs: producing JSON text correctly (escaping is where beginners go wrong), a typed tree for JSON values using a sealed interface, and a small parser. The full-size version of the parser is built in Project: A JSON Parser.

Building JSON text

The simplest way to produce JSON is buildString and string templates. It works for small, fixed shapes:

Kotlin JSON from a template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Raw strings ("""...""") let the double quotes stay unescaped, which keeps the template readable. But this approach has a hidden bug, which the next example exposes.

Escaping: the part you must not skip

Inside a JSON string, the characters " and \ and all control characters (newline, tab, and so on) must be written as escape sequences: \", \\, \n, \t, or \u00XX. If a name contains a quote and you paste it in unescaped, the output is broken JSON, or worse, an injection hole where user input changes the structure of your document.

Kotlin Why unescaped text breaks JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output has a quote in the middle of the string and a real line break, so no JSON parser will accept it. The fix is a function that escapes every string before it is placed in the document:

Kotlin An escape function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The control character with code 7 becomes \u0007. Non-ASCII characters like รฉ do not have to be escaped, because JSON text is normally UTF-8. Whenever you build text for another language (JSON, SQL, HTML, a shell command), the rule is the same: never insert raw user input; escape it for the target format.

A typed tree of JSON values

To build bigger documents safely, model JSON itself in Kotlin. A sealed interface lists the six kinds of value, and a function walks the tree and prints it. Because when over a sealed type must be exhaustive, the compiler tells you if you forget a case.

Kotlin Modeling JSON with a sealed interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

linkedMapOf keeps the keys in the order we wrote them (see maps); with a plain HashMap the order could change. The sealed tree gives you something a string template never can: the structure is checked by the compiler, and escaping happens in exactly one place.

Parsing JSON by hand

Reading JSON is harder than writing it, because input can be malformed and you must report where. A recursive descent parser has one function per kind of value; each function consumes characters from a shared position and calls the others for nested parts. The class below handles the whole format except \u escapes, which is enough to show the idea.

Kotlin A tiny recursive descent parser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Read the structure, not every line. value() looks at the first character and picks the right parser. arr() and obj() call value() again for every element, which is the recursion. fail returns Nothing, so the compiler knows that the code after it cannot continue (see Any, Unit and Nothing). The error messages carry a position, so a user can find the mistake in a large file.

Reading values out of the tree

Once parsed, you navigate the tree with safe casts and when. Extension operators on the nullable type Json? make lookups readable, and a missing step simply gives null:

Kotlin Querying a parsed tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The last two lines print null and do not crash, because every step is a nullable lookup (see null safety).

Libraries: kotlinx.serialization

For real applications, you do not write parsers. kotlinx.serialization generates the code for your data classes at compile time. This snippet is read-only because the library and its compiler plugin need a Gradle build (see Gradle basics):

Kotlin
// read-only example: needs the serialization Gradle plugin and library
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
data class User(val name: String, val age: Int, val tags: List<String> = emptyList())

fun main() {
    val text = Json.encodeToString(User("Ada", 36, listOf("math")))
    println(text)                                  // {"name":"Ada","age":36,"tags":["math"]}
    val user = Json.decodeFromString<User>(text)
    println(user)                                  // User(name=Ada, age=36, tags=[math])
}

Other common choices are Jackson and Moshi (on the JVM) and Gson. Use a library whenever data crosses a trust boundary: it is faster, handles every escape and number format, and reports clear errors. Parse by hand only for tiny formats, for learning, or when you cannot add dependencies.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is """{"name": "$name"}""" a bad way to produce JSON for arbitrary names?

    The value is pasted in as it is. A quote or newline in the name breaks the document and can change its structure.
  2. 2. What does a sealed interface give you when modeling JSON values?

    Sealed hierarchies have a closed set of subtypes, so a when over them without an else branch must cover every case.
  3. 3. Why do the parser's fail and expect helpers matter for error messages?

    The exception carries the current position, which is the most useful piece of information for malformed input.
  4. 4. When should you prefer kotlinx.serialization over a hand-written parser?

    Libraries handle all escapes, numbers and error cases and generate code for your classes. Hand-written parsing is for learning and very small formats.

Summary

  • JSON has six kinds of value: object, array, string, number, boolean and null.
  • Build small documents with buildString or templates, but always escape strings (", \, control characters).
  • Model JSON as a sealed interface to get a checked, exhaustive tree.
  • A recursive descent parser has one function per kind of value and reports a position on errors.
  • Safe-call lookups (?., getOrNull) make navigating a parsed tree crash-free.
  • In real projects use kotlinx.serialization, Jackson or Moshi instead of hand-written code.

Next: Introduction to Coroutines