CodeGym /Courses /Kotlin SELF /Basic pipeline encode/ decode + storing JSON in a file

Basic pipeline encode/ decode + storing JSON in a file

Kotlin SELF
Level 47, Lesson 3
Available

1. What we build today: object → JSON string → file → object

When you first hear “object to a file”, your brain often imagines some kind of magic like “put a variable into a file — pull it out tomorrow exactly the same”. In reality, there is no magic: a file can store bytes/text, not Kotlin objects. So we will build a very honest pipeline: first we turn an object into a JSON string, then we write that string to a file. After that, we read the string from the file and turn it back into an object.

To keep all examples tied into one application, we will continue our hypothetical console mini-project: an expense tracker (Expense Tracker). Still no database, no networking, and no “grown-up” architecture — for now, it is more important to learn how to save and load data so that tomorrow the app does not start life from a blank slate and a sad println("Well then, everything by hand again?").

Pipeline diagram

flowchart LR
    A[Expense / List⟨Expense⟩
v pamyati] --> B[encodeToString
JSON String] B --> C[writeText
expenses.json] C --> D[readText
JSON String] D --> E[decodeFromString
List⟨Expense⟩]

2. Step 1: object → JSON string

When we say “serialize to JSON”, we basically mean: “make a string from an object — one that you can print in the console, write to a file, send anywhere”. And here it is very important not to mix things up: toString() also returns a string, but it is not a data format — it is just a technical representation “for a human and for debugging”. JSON is a format that the library can read back, and it can be treated as a contract.

A mini-model for our application

Assume that in the previous lecture (about @Serializable) we already created this expense model:

import kotlinx.serialization.Serializable

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

Everything here is as down-to-earth as it gets: id is an integer, title is a string, amount is also an integer (for example, dollars/francs without cents — not ideal, but enough to start), category is a string, and note is nullable so we can practice null.

The simplest encoding: one object

First, without files and without lists — just to see “what we get at all”. To encode to a string, we use Json.encodeToString(...):

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

fun main() {
    val e = Expense(id = 1, title = "Coffee", amount = 250, category = "Food")
    val jsonText = Json.encodeToString(e)

    println(jsonText)
    // {"id":1,"title":"Coffee","amount":250,"category":"Food","note":null}
}

Notice: the JSON came out “compact”, without line breaks. That is normal. Making it pretty for humans is something we will do in the next lecture about Json { ... } settings, but for now it matters more that it works reliably as a storage format.

Encoding a list of expenses

Our app typically stores not one expense but a list. JSON for a list looks like an array [...], and the library supports this directly:

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

fun main() {
    val expenses = listOf(
        Expense(1, "Coffee", 250, "Food"),
        Expense(2, "Transit", 60, "Transport", note = "Metro"),
    )

    val jsonText = Json.encodeToString(expenses)
    println(jsonText)
    // [{"id":1,"title":"Coffee","amount":250,"category":"Food","note":null},{"id":2,"title":"Transit","amount":60,"category":"Transport","note":"Metro"}]
}

It is useful to keep a simple mapping in mind: List<Expense> turns into a JSON array [...], and each Expense inside turns into a JSON object {...}.

3. Step 2: JSON string → object

Now we go in the opposite direction. The idea of deserialization is simple: we have a JSON string, and we want to get a Kotlin object of the required type. The important point is that the type must be specified. A JSON string by itself does not say “I am a User” or “I am an Expense”. It is just data, and the type is a decision made by your code.

To avoid illusions, here is the honest truth: this step can fail with an error if the JSON does not match the model. And that is normal. We are learning to live in a world where input data can be “dirty”.

For decoding we use Json.decodeFromString<T>(...).

Decode one object

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

fun main() {
    val input = """{"id":10,"title":"Tea","amount":120,"category":"Food","note":null}"""
    val e = Json.decodeFromString<Expense>(input)

    println(e)
    // Expense(id=10, title=Tea, amount=120, category=Food, note=null)
}

Pay attention to <Expense>: we explicitly say “read this as Expense”.

Decode a list

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

fun main() {
    val input = """[{"id":1,"title":"Coffee","amount":250,"category":"Food","note":null}]"""
    val expenses = Json.decodeFromString<List<Expense>>(input)

    println(expenses.size)     // 1
    println(expenses[0].title) // Coffee
}

If you confuse {} with [], you will get an error. This is one of the most common bugs: you think the file contains one object, but it is an array, or vice versa. So before decoding it helps to at least do a quick “eyeball check” of what the string starts with: { or [.

4. Step 3: a file as transport for the string

At this stage we do an important mental shift: a file does not “store objects”, a file “stores a string”. We simply agree that this string will be JSON.

From a code perspective, this means operations split into two independent parts: serialization (to a string) and I/O (to a file). This separation helps debugging a lot: if something breaks, you immediately understand whether the problem is JSON or the path/permissions/directory.

Write a JSON string to a file

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

fun main() {
    val dir = File("data")
    dir.mkdirs()

    val file = File(dir, "expenses.json")
    val text = Json.encodeToString(listOf(Expense(1, "Coffee", 250, "Food")))

    file.writeText(text)
    println("Saved to ${file.path}") // Saved to data/expenses.json
}

The key point is dir.mkdirs(): if the folder does not exist, writing can fail. Yes, computers sometimes require you to create the folder first. They are stubborn, but honest.

Read a JSON string from a file

import java.io.File

fun main() {
    val file = File("data/expenses.json")
    val text = file.readText()

    println(text) // JSON content as a single line
}

Everything here is as straightforward as possible: read the string — and then you can pass it to decodeFromString.

5. Mini-pipeline: save and load a list

Now let’s glue everything into two steps: save the list and then load it. To make the code easier to read and reuse, we will extract small functions. This is not “architecture for decades”, just a human habit: do not write the same code in three places.

Save function

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

fun saveExpenses(file: File, expenses: List<Expense>) {
    val text = Json.encodeToString(expenses)
    file.parentFile?.mkdirs()
    file.writeText(text)
}

Here we add a small safeguard: file.parentFile?.mkdirs() creates the directory if it exists (and if parentFile is not null). This is convenient when you pass a path like "data/expenses.json".

Load function

import java.io.File
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json

fun loadExpenses(file: File): List<Expense> {
    if (!file.exists()) return emptyList()

    val text = file.readText()
    return Json.decodeFromString(text)
}

An important UX point: if the file does not exist, that is not a “world error”. It is a normal situation on the first run. So instead of crashing, we return emptyList().

Notice: Json.decodeFromString(text) works without an explicit <List<Expense>>, because the compiler can infer the type from the function’s return type. If loadExpenses returned Any, we would have to specify the type explicitly — but we will not do that; we want to be friends with the compiler, not fight it.

Verify in main that round-trip works

Now we will write a small main that creates a list of expenses, saves it, loads it back, and prints the result. This is an important ritual: first make sure the pipeline works in a vacuum, and only then attach it to commands like add/list/remove (which you may have implemented earlier).

import java.io.File

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

    val expenses = listOf(
        Expense(1, "Coffee", 250, "Food"),
        Expense(2, "Transit", 60, "Transport", note = "Metro"),
    )

    saveExpenses(file, expenses)

    val loaded = loadExpenses(file)
    println("Loaded: ${loaded.size}") // Loaded: 2
    println(loaded[0])                // Expense(id=1, title=Coffee, amount=250, category=Food, note=null)
}

If this example works, the foundation is ready: we have learned how to store data “between runs”. That is already almost an adult program (just a little left: stop breaking on every weird file).

Plug the file into a CLI expense tracker

When you build (or have already built) a console interface with commands like add, list, remove, it is important to integrate the file correctly: loading should happen at program start, and saving should happen after changes. If you only save at the end and the program crashes earlier, the data is lost. If you save after each command, it becomes almost impossible to lose data (and yes, it writes to the file a bit more often, but for a learning project that is fine).

Below is a very simplified main “skeleton”, without complex command parsing. It shows the idea: “load → change → save”.

import java.io.File

fun main() {
    val file = File("data/expenses.json")
    val expenses = loadExpensesSafe(file).toMutableList()

    expenses.add(Expense(3, "Cookies", 90, "Food"))
    saveExpenses(file, expenses)

    println("Now total: ${expenses.size}") // Now total: 3
}

The key idea here: in memory we work with a list (MutableList), but in the file we store a JSON string. The file is not “smarter” than the list. It simply stores the result of serialization.

6. Errors and diagnostics: where loading fails

Any “load data” operation lives in a harsh world. The file may be missing, may be empty, may be corrupted, may not be JSON, may be JSON but in the wrong format. And if you do not separate the “read the string” step from the “parse JSON” step, diagnostics turn into fortune-telling on coffee grounds (in our expense app, that is especially fitting).

Two classes of problems

In practice, problems almost always split into two big categories:

Where it broke What it looks like What it means in plain language
I/O (file) not found, no permissions, directory instead of a file “we could not obtain the string”
JSON/type parsing error, type mismatch “we got the string, but it does not match the model”

Minimal diagnostics via try/catch

Let’s create a version of loadExpenses that does not crash, but returns an empty list and prints a clear message. This is not a perfect strategy for all programs, but for a learning console app it is a great start.

import java.io.File
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json

fun loadExpensesSafe(file: File): List<Expense> {
    if (!file.exists()) return emptyList()

    return try {
        val text = file.readText()
        Json.decodeFromString(text)
    } catch (e: Exception) {
        println("Failed to load ${file.path}: ${e.message}")
        emptyList()
    }
}

Why catch Exception and not something more specific? Because our goal right now is to learn not to crash and to see a message. You can narrow down exception types later, when you feel confident. At this level, the key is understanding the principle: “read” and “parse” are different steps.

7. Common mistakes

Mistake No. 1: trying to “save an object” via toString().
A data class has a very convenient toString(), and it really looks “almost like data”. But it is a trap: it is a debug string, not a storage format. Today you saved Expense(id=1, title=Coffee, ...), and tomorrow you changed the field order or a property name — and the “format” suddenly became different. JSON, on the other hand, is produced by the library and read by the library, so the round-trip actually makes sense.

Mistake No. 2: mixing I/O and JSON into one blob and then not understanding where it failed.
If you do Json.decodeFromString(File("x").readText()) in a single line, then on error you see an exception but do not understand whether the problem was reading the file or parsing. When you keep the steps separate, debugging becomes almost boring: “file read OK — here is the string — parsing failed — therefore JSON does not match”.

Mistake No. 3: not creating the directory before writing.
File("data/expenses.json").writeText(...) looks nice, but if the data folder does not exist, the write may fail. Because of this, beginners sometimes think “serialization does not work”, while serialization did work and writing failed. Create the directory via mkdirs() (or via file.parentFile?.mkdirs() inside the save function).

Mistake No. 4: decoding the wrong top-level: {} instead of [].
If you save a list of expenses, the file will contain a JSON array [...]. If you then mistakenly try to decode it as a single Expense, you will get an exception. The simplest self-check is to look at the first character of the JSON: { means an object, [ means a list.

Mistake No. 5: treating a missing file as an error.
The first run of a program almost always happens without a file. If you crash with an exception here, you are building an app that cannot start life. It is better to treat “file does not exist” as “no data yet” and return emptyList() — it is much friendlier to the user (and to you when testing).

Mistake No. 6: thinking that “if JSON parsed, then the data is correct”.
Parsing validates structure and types, but not meaning. For example, amount = -999999 can parse just fine. So it helps to remember: serialization/deserialization is the “data shape” layer, while correctness checks are separate application logic. Today we just draw this boundary so we do not demand the impossible from JSON.

1
Task
Kotlin SELF, level 47, lesson 3
Locked
Profile Backup
Profile Backup
1
Task
Kotlin SELF, level 47, lesson 3
Locked
Task synchronization
Task synchronization
1
Task
Kotlin SELF, level 47, lesson 3
Locked
Settings file
Settings file
1
Task
Kotlin SELF, level 47, lesson 3
Locked
Bookshelf
Bookshelf
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION