CodeGym /Courses /Kotlin SELF /Configuring Json { ... }: readability, compatibility, str...

Configuring Json { ... }: readability, compatibility, strictness

Kotlin SELF
Level 47, Lesson 4
Available

1. Json { ... } is part of the data contract

When you first see Json { prettyPrint = true }, it’s tempting to think: “Oh, that’s just to make it look pretty.” Partly yes, but in practice the Json settings are an agreement about the format — almost like “traffic rules” for your file. One team writes JSON, another team reads JSON, and both must interpret the same way which fields may be absent, what to do with null, and how tolerant we are of “slightly wonky” input.

It’s important to catch the idea: Json is not “JSON in general”, but a specific codec with specific rules. If in one part of the project you do Json.encodeToString(...) (with the default object), and elsewhere you create Json { ignoreUnknownKeys = true } and read with it, then you already live in two slightly different worlds. And the bugs will be of the “but it worked for me…” kind, because it worked in a different world.

Let’s choose the right habit up front: the application should have one (or a very limited number) of Json instances, created explicitly and used everywhere.

A small “skeleton” to start with:

import kotlinx.serialization.json.Json

private val appJson = Json {
    prettyPrint = true
}

2. Settings that make a file convenient for humans

prettyPrint: readability and diffs

When you store JSON in a file (settings, app data, results), sooner or later you’ll open it with your own eyes. Sometimes voluntarily, sometimes because “something broke and the deadline is on fire.” And here the difference between one-line JSON and indented JSON is roughly like the difference between “everything in one paragraph with no spaces” and “normal text.”

The option prettyPrint = true enables formatting: line breaks and indentation. The meaning of the data doesn’t change; only the appearance changes. This is handy for debugging, manual checking, and even for Git (diffs become more readable).

First, let’s show the effect on a minimal example.

import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
data class User(val id: Int, val name: String)

fun main() {
    val user = User(1, "Ada")

    val compact = Json { prettyPrint = false }
    val pretty = Json { prettyPrint = true }

    println(compact.encodeToString(user)) // {"id":1,"name":"Ada"}
    println(pretty.encodeToString(user))  // (will have line breaks and indentation)
}

If you want to see the output neatly in the console without “staircases” of spaces in the code, it’s convenient to print multi-line strings via trimIndent() — it’s a good habit for any triple-quoted strings, not only for JSON.

A slightly more “applied” example: in our learning expense-tracker app (let’s call it BudgetCLI) we store data in data/state.json. When prettyPrint is enabled, the file becomes “self-documenting”: even a beginner can see the structure.

encodeDefaults: write defaults explicitly or save space

Kotlin (and especially data class) loves default values: they make constructors convenient and help keep the model valid. But JSON can be written in two ways:

  • write all fields, even those that equal their default value;
  • write only the “essential” fields, and restore the rest to defaults when reading.

The option encodeDefaults controls this behavior during encoding (writing to JSON).

Why does this matter? Because it affects what you consider the “truth of the format.” If a field is not written, then it is “as if” it equals the default — but only if the reading side also knows about that field and its default. If you want the JSON to be as explicit as possible (for example, for configurations), then it makes sense to write defaults.

Let’s look at a small “settings” example:

import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
data class Settings(
    val theme: String = "light",
    val pageSize: Int = 20
)

fun main() {
    val a = Json { encodeDefaults = false }
    val b = Json { encodeDefaults = true }

    println(a.encodeToString(Settings())) // {}
    println(b.encodeToString(Settings())) // {"theme":"light","pageSize":20}
}

This is the point where beginners often get surprised: “Why is {} even valid settings?” Because the Kotlin model can be fully restored from defaults. And it’s even convenient: minimal file, less noise.

But there’s a flip side. If you store a file as an agreement that must be self-sufficient, then {} looks like it’s mocking the person who opened the file by hand to “check the settings.” So choosing encodeDefaults is not about “right/wrong”, but about UX and contract stability.

For our BudgetCLI, a reasonable approach is often: we write the data (expenses) fully, but we can write UI/sorting settings more compactly. However, to avoid creating two different worlds, people often pick one style for the whole project and live happily.

explicitNulls: “field = null” and “field is missing” are different states

Nullable fields are normal. Not everyone likes null, but it stubbornly returns to our lives like a cat that “will just take a look” and then accidentally eats your fish.

In JSON, there are two different states:

  • the field is present and equals null: "note": null
  • the field is not present at all: (the key is missing)

To a human, this looks similar (“well, there’s basically nothing here”), but for a program these are sometimes fundamentally different situations. For example, “the user explicitly cleared the note” vs “older files didn’t have notes at all.”

The option explicitNulls controls whether null will be written to JSON explicitly or omitted.

Let’s make an expense model with a nullable note:

import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
data class Expense(
    val title: String,
    val amount: Double,
    val note: String? = null
)

fun main() {
    val x = Expense(title = "Coffee", amount = 3.5, note = null)

    val a = Json { explicitNulls = true }
    val b = Json { explicitNulls = false }

    println(a.encodeToString(x)) // {"title":"Coffee","amount":3.5,"note":null}
    println(b.encodeToString(x)) // {"title":"Coffee","amount":3.5}
}

This is where grown-up format architecture begins: if you choose explicitNulls = false, the file has less clutter and looks nicer. But you lose the ability to distinguish “the value is absent because it wasn’t in the file” from “the value is absent because we wrote it as null (or decided to omit it).” In our simple console app this is usually not critical, but it’s important to understand the difference itself; otherwise you can end up arguing with a colleague for a long time about “why did my field get reset.”

3. Reading settings: compatibility and tolerance

ignoreUnknownKeys: compatibility when reading old and new files

Imagine a real-life situation: you saved data in JSON, then updated the program, changed the model (for example, added a new field), and the user still has an old file. Or the other way around: the file came from somewhere else and contains more fields than your current model. At that moment serialization turns into a very principled inspector: “Extra field? Not wearing the proper uniform? Goodbye.”

The option ignoreUnknownKeys = true tells the parser: “If the JSON has fields that aren’t in the model, just skip them.” This greatly improves compatibility. But, like any “concession”, it can hide a problem: if you expected a field but misspelled its name, then with ignoreUnknownKeys enabled you won’t see an error — the field will simply be ignored.

Mini demo:

import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json

@Serializable
data class User(val id: Int, val name: String)

fun main() {
    val input = """{"id":1,"name":"Ada","age":20}"""

    val strict = Json { ignoreUnknownKeys = false }
    val tolerant = Json { ignoreUnknownKeys = true }

    // strict.decodeFromString<User>(input)  // will crash: field "age" is unknown
    val user = tolerant.decodeFromString<User>(input)
    println(user) // User(id=1, name=Ada)
}

Now let’s tie this to our BudgetCLI. Suppose we added the note field to expenses, but someone’s file already contains a currency field as well (for example, added by another teammate or an older version). If we enable ignoreUnknownKeys, reading doesn’t break: we load what we understand and ignore the rest.

In practice this is a very common “first toggle” that gets enabled in projects with files and long-term data storage. But it’s worth enabling consciously: if the format is fully under your control and you want to catch any mismatches strictly, strict mode also has a right to exist.

isLenient: a tolerant parser for import, but not for “your own” format

Sometimes the data doesn’t come from your file, but “from somewhere”: the user copied JSON from the internet, someone edited the file by hand, or another system generates almost-JSON (yes, such systems exist; apparently they’re just bored with living by the standard). At that point a strict JSON parser becomes your enemy: it fails on any deviation from the format.

The option isLenient = true makes the parser more tolerant of certain non-strict cases. The idea is precisely to read something that looks like JSON, even if it isn’t perfect according to the spec. But the price is a blurrier contract: you start “accepting whatever”, and then wonder why a strange format suddenly appears in the file.

Within this course, a good practical rule is: for your own files (that you also write yourself), isLenient is usually unnecessary. For importing external data, it can sometimes be useful, but you should enable it only where you are truly ready to accept “dirty” input.

The code stub looks like this:

import kotlinx.serialization.json.Json

private val importJson = Json {
    isLenient = true
    ignoreUnknownKeys = true
}

Notice the combination: “format tolerance” plus “tolerance for extra keys” is a typical pairing for import. But this is import specifically, not the main writing of your state file.

4. A single Json for the application and file storage

Now we’ll take the most practical step: we’ll stop creating Json { ... } “on the fly” in every main, and introduce one codec instance for the whole app. It’s almost like a single quote style in a project: seems minor, but later it suddenly turns out to save hours of life.

Let’s assume our BudgetCLI stores state as a list of expenses.

Minimal model:

import kotlinx.serialization.Serializable

@Serializable
data class Expense(
    val title: String,
    val amount: Double,
    val category: String = "other",
    val note: String? = null
)

@Serializable
data class BudgetState(
    val expenses: List<Expense> = emptyList()
)

Now — a single codec. I’ll pick a set of settings that usually works well for “a file on disk that you can open with your eyes”:

  • prettyPrint = true — readability
  • ignoreUnknownKeys = true — compatibility when reading old/new files
  • encodeDefaults = true — self-sufficient file, fewer surprises
  • explicitNulls = false — to avoid generating "note": null everywhere
import kotlinx.serialization.json.Json

private val appJson = Json {
    prettyPrint = true
    ignoreUnknownKeys = true
    encodeDefaults = true
    explicitNulls = false
}

And now the save/load functions (keep them short and “to the point”):

import java.io.File
import kotlinx.serialization.encodeToString

fun saveState(file: File, state: BudgetState) {
    val text = appJson.encodeToString(state)
    file.parentFile?.mkdirs()
    file.writeText(text)
}
import java.io.File
import kotlinx.serialization.decodeFromString

fun loadState(file: File): BudgetState? {
    return try {
        if (!file.exists()) return null
        val text = file.readText()
        appJson.decodeFromString<BudgetState>(text)
    } catch (e: Exception) {
        null
    }
}

And a small main that shows everything works:

import java.io.File

fun main() {
    val file = File("data/state.json")

    val state = BudgetState(
        expenses = listOf(
            Expense(title = "Coffee", amount = 3.5, category = "food"),
            Expense(title = "Book", amount = 12.0, note = "Kotlin")
        )
    )

    saveState(file, state)

    val loaded = loadState(file)
    println(loaded) // BudgetState(expenses=[Expense(...), Expense(...)])
}

What matters here is not “how cool the app is”, but boundary discipline: Json is responsible for formatting and encoding/decoding rules, the file is responsible for transporting the string, and main is responsible for the scenario. When these layers are not mixed, debugging is much easier.

A small diagram to cement the data flow in your head:

flowchart TD
    A[BudgetState v pamyati] --> B[appJson.encodeToString]
    B --> C[JSON-stroka]
    C --> D[file.writeText]
    D --> E[file.readText]
    E --> F[appJson.decodeFromString]
    F --> G[BudgetState v pamyati]

5. Typical mistakes when configuring Json

Mistake #1: “In one place I write Json.encodeToString, and in another I read with my own Json { ... } — so what?”
The problem is that these are two different sets of rules. Today they are accidentally compatible, and tomorrow you’ll enable encodeDefaults or change explicitNulls, and you’ll start seeing strange situations: the file looks one way, but the program expects another. A simple rule saves you: one appJson per application and no “accidental” Json in the middle of the code.

Mistake #2: enable ignoreUnknownKeys = true and stop noticing key errors.
This setting saves compatibility, but it can hide typos. If the JSON field is named "catrgory" instead of "category", it will be ignored, and you’ll get the default value. For the user this looks like “the program lost the data.” So it’s good to at least sometimes check the input JSON visually or log the fact of loading/errors (in our simplified example, we still just return null).

Mistake #3: think that prettyPrint changes the data rather than the representation.
Sometimes students start thinking that “pretty JSON” is a different format and needs separate support. No: it’s the same JSON, just with spaces and line breaks. It should be read by a normal parser exactly the same as the compact version.

Mistake #4: not understand the difference between “field is missing” and “field = null”, and then be surprised by the behavior of explicitNulls.
If you don’t distinguish these states, you can accidentally lose meaning. For example, “the note is absent because this is an old file version” and “the note is absent because the user deleted it” can be different events. explicitNulls affects whether you’ll later be able to tell these cases apart by the file.

Mistake #5: enable isLenient “just in case.”
This is almost always a bad idea for the application’s own files. You generate the JSON yourself, so why weaken the checks? Tolerance is needed for importing someone else’s data, but there it should be limited via a separate codec or a separate function so that “dirty input” doesn’t leak into the main storage format.

Mistake #6: change Json settings and forget that this changes the storage format.
The nastiest trap: you changed encodeDefaults or explicitNulls, wrote a new file, and then try to read it with an older version of the program or another part of the project. So treat the settings as part of the format: if you change them, it’s a contract change, not “refactoring without consequences.”

1
Task
Kotlin SELF, level 47, lesson 4
Locked
Two formats
Two formats
1
Task
Kotlin SELF, level 47, lesson 4
Locked
Empty defaults
Empty defaults
1
Task
Kotlin SELF, level 47, lesson 4
Locked
Null traces
Null traces
1
Task
Kotlin SELF, level 47, lesson 4
Locked
Tolerant parser
Tolerant parser
1
Survey/quiz
JSON + kotlinx.serialization, level 47, lesson 4
Unavailable
JSON + kotlinx.serialization
JSON + kotlinx.serialization
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION