1. Parsing and validation: roles and the result contract
Even if JSON was parsed successfully, that still does not mean the data fits our application. In this lecture, we will build a validation layer that turns JsonElement into normal Kotlin data (or a clear error) and does so without using exceptions as the “default” mechanism for controlling program logic.
When you start accepting data “from the outside world” (a file, a user, someone else’s service), it is very tempting to hope for the best: “well, it says amount, so it must be a number.” Reality is usually less romantic: the field may be missing, may be null, may be a string "100", may be a string "one hundred", or it may even be named differently. That is why we need discipline: first answer “is this even JSON?”, and then — “is this the data we are ready to process?”.
Parsing vs validation
Parsing is a syntax check. In other words, “the string follows the JSON rules.” If a comma or a quote is missing, the parser will say “can’t do it” (and that is normal). Validation is a check of the meaning and the application requirements: fields are present, types are correct, values are within reasonable ranges, strings are not empty, numbers are not negative, and so on.
It helps to keep this diagram in mind (it will also be our function architecture):
flowchart LR
A["String (JSON text)"] --> B["parseToJsonElement()"]
B -->|success| C["JsonElement (tree)"]
B -->|error| E["Error: 'invalid JSON'"]
C --> D["validate(...)"]
D -->|Ok| F["Valid Kotlin data"]
D -->|Error| G["Clear error for the user/log"]
The main benefit of this separation is that the code becomes predictable: we have one “point” where JSON becomes a tree, and a separate “point” where the tree becomes a valid model. If something is wrong, we understand exactly at which stage and why.
Why Boolean is not enough, and why Ok/Error
When a beginner writes “validation”, they often end up with a function like fun isValid(x): Boolean. That is not a bad start, but it breaks against reality: if validation returns false, we need to understand why. Otherwise the app becomes a fortune teller: “the data is invalid… which data? where? what should be fixed?”.
So we give our validator an adult contract: it returns either success or an error with a message. At this stage, let’s agree not to “collect a bag of 17 errors at once”, but to return a single reason — it is simpler both for the code and for the user.
Let’s make a universal result type:
sealed class ValidationResult<out T> {
data class Ok<T>(val value: T) : ValidationResult<T>()
data class Error(val message: String) : ValidationResult<Nothing>()
}
Two things are important here. First, Ok stores an already prepared value of the required type T, so the subsequent code works with normal data instead of continuing to “poke JSON with a stick”. Second, Error stores a message that can be shown to the user or written to a log (in a console project, those are often almost the same thing).
And one more bonus: sealed class works great with when — the compiler forces us to handle all variants (meaning we will not forget about the error case and pretend everything is fine).
2. Mini-story: importing expenses into a CLI app
So that the examples are not “in a vacuum”, let’s continue developing our educational console app — a hypothetical Expense Tracker. Earlier we could already store expenses and serialize them to JSON via @Serializable, but today the scenario is different: imagine we were sent JSON of an unknown format (or “almost ours”, but with surprises), and we want to import it.
We will validate one expense entity with the fields:
- title: a string, non-empty (for example, "Coffee")
- amount: an integer, strictly greater than zero (for example, 250)
- category: a string (may be empty/missing — then we will substitute "other")
Let’s create the model of “already normalized data” that we get after validation:
data class ExpenseDraft(
val title: String,
val amount: Int,
val category: String
)
Why Draft? Because it is a “draft” after validating the input: we are not talking about saving, IDs, and so on yet. We just want to guarantee the data is sane and safe for the rest of the logic.
3. Pipeline: parse JSON and validate the data
A very common mistake is to make one giant function that parses, validates, prints, and “just in case” catches all exceptions. It typically looks like a combine harvester: heavy, brittle, and scary. We will do it more neatly: parseJson(text) is responsible only for whether the text is valid JSON; validate... is responsible only for whether the structure and values fit.
Parse text into a JsonElement tree
parseToJsonElement can throw an exception if the text is not valid JSON, so we will honestly catch the error and return Error:
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
fun parseJson(text: String): ValidationResult<JsonElement> {
return try {
ValidationResult.Ok(Json.parseToJsonElement(text))
} catch (e: Exception) {
ValidationResult.Error("Invalid JSON: ${e.message}")
}
}
Notice: we do not do any field checks for amount/title here. For now we only care about one thing: “was the tree built or not”.
Helper functions: less copy-paste, more meaning
A validator almost always consists of repeated steps: “get a field”, “ensure it is a primitive”, “take its string representation”, “convert it”. If you write this by hand every time, you will very quickly start hating JSON, life, and your keyboard.
So we will reuse helper functions:
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
fun getPrimitiveOrNull(obj: JsonObject, key: String): JsonPrimitive? {
val el = obj[key] ?: return null
return el as? JsonPrimitive
}
import kotlinx.serialization.json.JsonObject
fun getStringOrNull(obj: JsonObject, key: String): String? =
getPrimitiveOrNull(obj, key)?.content
import kotlinx.serialization.json.JsonObject
fun getIntOrNull(obj: JsonObject, key: String): Int? {
val text = getStringOrNull(obj, key) ?: return null
return text.toIntOrNull()
}
There is a “philosophy” here: these functions do not throw exceptions and do not substitute default values. They simply say: “if I can read it correctly — I did; if I can’t — I returned null”. And then the validator decides whether null is acceptable or an error.
Validate a single expense: JsonElement -> Ok(ExpenseDraft) / Error(message)
Now the tastiest part: turn a piece of JSON into normal data. We expect an object (JsonObject), check fields, check constraints, and return a result. It is important to keep the order of checks: first structure (is it an object or not), then presence/type, then rules (ranges, blank strings).
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
fun validateExpense(el: JsonElement): ValidationResult<ExpenseDraft> {
val obj = el as? JsonObject ?: return ValidationResult.Error("Expense must be a JSON object")
val title = getStringOrNull(obj, "title")?.trim()
?: return ValidationResult.Error("Field 'title' is required")
if (title.isBlank()) return ValidationResult.Error("Field 'title' must be non-blank")
val amount = getIntOrNull(obj, "amount")
?: return ValidationResult.Error("Field 'amount' must be an integer")
if (amount <= 0) return ValidationResult.Error("Field 'amount' must be positive")
val categoryRaw = getStringOrNull(obj, "category")?.trim()
val category = if (categoryRaw.isNullOrBlank()) "other" else categoryRaw
return ValidationResult.Ok(ExpenseDraft(title = title, amount = amount, category = category))
}
Notice the style: many early return. This is not “laziness”, but a practical guard-clauses technique: as soon as we detect a problem — we immediately return an error and do not continue computations in a “broken” state.
One more point: we normalize the data. We call trim() on strings, and we convert an empty/missing category to "other". Thanks to this, the rest of the code has fewer conditions and fewer chances to crash the app due to an empty string.
Validate a list: add an index and stop on the first error
Imports almost always come as a list: an array of expenses. And here an additional question appears: if one item is bad, what do we do with the rest? Within this lecture, we will choose the “fail fast, but nicely” strategy: as soon as we see an error — we stop and return Error, but we include the item index in the message. This already makes debugging the data much easier.
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
fun validateExpenses(el: JsonElement): ValidationResult<List<ExpenseDraft>> {
val arr = el as? JsonArray ?: return ValidationResult.Error("Root must be a JSON array")
val items = mutableListOf<ExpenseDraft>()
for ((index, itemEl) in arr.withIndex()) {
when (val r = validateExpense(itemEl)) {
is ValidationResult.Ok -> items.add(r.value)
is ValidationResult.Error -> return ValidationResult.Error("Item[$index]: ${r.message}")
}
}
return ValidationResult.Ok(items)
}
Yes, we could “collect all errors”, but that is a separate (and more complex) technique. Right now it is more important to learn how to keep the code simple and predictable: one error — one clear answer.
Glue the pipeline in main: readability matters more than “everything in one line”
When everything is ready, you want to make it elegant: “parse, validate, move on” in one line. But for beginners this often turns into magic that is hard to debug. So we will assemble the pipeline explicitly, via intermediate vals. This code looks a bit longer, but it is easy to read and easy to fix.
import kotlinx.serialization.json.JsonElement
fun main() {
val text = """
[
{"title":"Coffee","amount":250,"category":"food"},
{"title":"Book","amount":900,"category":"education"}
]
""".trimIndent()
val parsed: ValidationResult<JsonElement> = parseJson(text)
when (parsed) {
is ValidationResult.Ok -> {
val validated = validateExpenses(parsed.value)
println(validated) // Ok(value=[ExpenseDraft(...), ...]) or Error(...)
}
is ValidationResult.Error -> println(parsed.message) // Invalid JSON: ...
}
}
Here you can clearly see the separation of responsibilities: parseJson handles syntax, validateExpenses handles application requirements. And yes, println(validated) prints a “technical” representation of the result; in a real CLI you would output more user-friendly messages, but that is a UI formatting question, not validation.
4. require() and check(): where they belong, and where Ok/Error belong
Sometimes a student reasonably asks: “Why all this ValidationResult, if we have require(condition) and check(condition)?” It is a good question, because Kotlin really can automatically throw exceptions via preconditions: require() throws IllegalArgumentException, and check() throws IllegalStateException. That is convenient and often makes code shorter.
But the nuance is what exactly you are checking. require() and check() are tools for situations where the program must not continue, because a contract has been violated: for example, the programmer called a function incorrectly, or an object ended up in an impossible state. Such checks are good in “internal” code, where errors mean a bug in the logic.
External data (JSON “from the street”) is not a bug in the program. It is a normal real-world situation: data can be corrupted, incomplete, incompatible by version. And in such cases, exceptions as the “normal control flow” often make code less readable. It is much nicer to return ValidationResult.Error("..."), show the user a clear message, and finish the import gracefully without crashing the whole program.
In short: require/check are about developer errors, Ok/Error are about input data errors.
5. Common mistakes when validating JSON data
Mistake #1: mixing parsing and validation in one “combine-harvester” function.
When one function simultaneously does parseToJsonElement, field checks, console printing, and writing into a collection, it becomes hard to understand at which step something broke. Splitting into two stages — parsing and validation — makes the code transparent: if it does not parse, the issue is syntax; if it parses but the validator complains, the issue is structure or values.
Mistake #2: using forced casts as and the !! operator when reading the tree.
Such code works exactly until the first surprise in the data, and then crashes at the worst possible moment. Validation is valuable because it should be resilient: as? plus a clear Error(...) is almost always better than “it must be an object, because I said so”.
Mistake #3: early substitution of a missing field with a default value that masks the problem.
If in a helper function you do “no amount — let it be 0”, the validator may “successfully” accept a record that is actually invalid. Much safer: the helper returns null, the validator decides whether it is an error or an acceptable absence, and only the validator has the right to substitute a default (as we did with category = "other").
Mistake #4: checking “business rules” before checking types and presence.
If you start by writing if (amount <= 0) before you even make sure that amount is a number, you will get either a mess of conditions or an exception. A stable order is usually: structure → presence → type → conversion → value constraints. Then the error messages will be clear and repeatable.
Mistake #5: returning Boolean instead of a result with a reason.
false does not explain what to fix. A message in Error is not a luxury; it is basic politeness toward your future self who, a week later, will be parsing someone else’s JSON at 2 a.m. and whispering: “who wrote this… oh right, me”.
GO TO FULL VERSION