1. Do we even need serialization?
A beginner’s first impulse is quite logical: “Can I just do println(user) and write that to a file? It already has text!” And this is where the classic trap begins: text is not always data. More precisely, text can be data, but only if it has clear formatting rules and we can later reconstruct the object back without guesswork.
toString() on a data class does indeed produce a nice-looking string like User(id=1, name=Ada). But this is not a format contract — it’s a debugging convenience. In the next version of the program you’ll rename a field, change the parameter order, add a new field — and old files will become “artifacts of an ancient civilization” that your own program won’t be able to read.
That’s why we need serialization: we want an object to be convertible into a storage/exchange format, and then restored back using clear rules. In our case we chose JSON, and that’s good news: JSON is readable by humans, stored in a file as plain text, and understood by almost all languages.
2. How kotlinx.serialization is structured
kotlinx.serialization is not just a set of functions like “make JSON for me”. An important part of this technology is that Kotlin enables a compiler plugin that can generate serialization code for your classes. That is, you write @Serializable data class User(...), and the compiler creates “invisible helpers” that know how to turn this User into a JSON structure and back.
It sounds mystical, but the idea is very practical: writing serialization by hand almost always ends in bugs, especially when you have nested objects, lists, nullable fields, and default values.
A small diagram to “make it click” what happens where:
flowchart TD
A[Your code: data class + @Serializable] --> B[Kotlin compiler + serialization plugin]
B --> C[Generated serializer code]
C --> D[Runtime library kotlinx-serialization-json]
D --> E[JSON text / JSON tree]
3. Adding it in Gradle
Adding serialization almost always breaks for beginners for one of two reasons: either they added the library but forgot the compiler plugin, or vice versa. So keep a simple rule in mind: you need both the dependency and the plugin. And yes, this is one of those moments when Gradle reminds you: “I’m not evil, I’m just config.”
Add the serialization plugin
In a Kotlin/JVM project on Gradle (with build.gradle.kts) you typically add the serialization plugin next to the main Kotlin plugin. It’s important that the serialization plugin version matches the Kotlin plugin version used by the project (in our course — Kotlin 2.3). If the versions diverge, you can get very strange errors that will confuse even the compiler.
An example snippet of build.gradle.kts (short, only the essentials):
plugins {
kotlin("jvm") version "2.3.0"
kotlin("plugin.serialization") version "2.3.0"
}
If your Kotlin version in the project is not "2.3.0" but something else (for example, "2.3.10"), then it must be the same here as well.
Add the dependency for the JSON module
Now let’s add the runtime library that provides Json and everything related to JSON specifics. Versions of kotlinx.serialization live their own life, so the exact number may change over time — but the principle is the same: add kotlinx-serialization-json in dependencies.
repositories {
mavenCentral()
}
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.0")
}
If you’re asking “is it definitely "1.7.0"?” — for a learning example, the structure matters more than the exact digit. You can change the version, but the plugin and Kotlin must get along with each other, otherwise the party ends before it begins.
Project sync
After editing the Gradle file you need to sync (in IntelliJ there is usually a button like “Load Gradle Changes” / “Sync”). Without it, the IDE may keep showing Unresolved reference even though you wrote everything correctly. It’s not mysticism — Gradle simply hasn’t downloaded the dependencies and rebuilt the project model yet.
4. The @Serializable annotation and models
The word “annotation” can easily sound like “something for grown-up developers who eat exceptions for breakfast”. But in essence an annotation is just a marker in code. It does not “run” like a function. It tells tools (the compiler, libraries, the IDE): “this element should be handled in a special way.”
In our case @Serializable is a marker: “generate a serializer for this class”. And then the compiler plugin does its part of the work.
Minimal example
import kotlinx.serialization.Serializable
@Serializable
data class User(
val id: Int,
val name: String
)
What matters here is that @Serializable is placed on the class. Today you don’t need to put it on individual fields (fine-grained format settings will come later).
The Expense model
So the examples aren’t “in a vacuum”, let’s continue a hypothetical practical console application — a simple expense tracker. Previously, we could store expenses in a MutableList<Expense> and print them to the console. Now we’re preparing to persist the state into a JSON file (but the actual encode/decode will be in the next lecture).
Let’s start with the expense model:
import kotlinx.serialization.Serializable
@Serializable
data class Expense(
val id: Int,
val title: String,
val amount: Int
)
The fields are as simple as possible: Int and String. This is intentional: the simpler the model at the start, the lower the chance you’ll “run into” a problem because of a type that serialization doesn’t understand.
The AppState model
Now let’s add an application state model so that later we can store not only the list of expenses, but also, for example, the next id:
import kotlinx.serialization.Serializable
@Serializable
data class AppState(
val nextId: Int,
val expenses: List<Expense>
)
Notice an important thing: if AppState contains Expense, then Expense must also be serializable. Otherwise the compiler will (rightfully) complain: “I don’t know how to serialize a field of this type.”
Nullable fields and default values
In practice, data is often incomplete: a comment may be missing, an extra description may be empty, and some field may appear later when you expand the program. So nullable types and default values are normal tools — it’s just important to understand that they affect what the data will look like in JSON (we’ll discuss the exact settings in the lecture about Json { ... }).
Let’s add an optional note and a currency with a default value to the expense:
import kotlinx.serialization.Serializable
@Serializable
data class Expense(
val id: Int,
val title: String,
val amount: Int,
val currency: String = "USD",
val note: String? = null
)
The idea is: old records may not have note, but the default currency is always present. This is a good step toward a “resilient” data format that doesn’t break from every sneeze.
5. Quick verification and project structure
Sometimes it seems like everything is added, but inside the project the plugin didn’t activate (or Gradle didn’t sync). You need a simple test that checks: “did the compiler actually generate a serializer?”
Verify that the plugin really works
One such test is to call serializer() on the class. If the serializer was generated, the code compiles.
import kotlinx.serialization.Serializable
@Serializable
data class User(val id: Int, val name: String)
fun main() {
val s = User.serializer()
println(s.descriptor.serialName) // User
}
If you get a compilation error here, the cause is almost always the setup: either you forgot kotlin("plugin.serialization"), or the dependency didn’t download, or the project wasn’t re-synced. And yes, this is that rare case where “rebuild the project” is not shamanism — it’s real diagnostics.
Where to keep models and how not to create a mess
When you add serialization, it’s tempting to smear @Serializable all over the project, and keep classes next to main because “it’s faster”. It is faster — until the first moment when you can’t find where your Expense is, where your AppState is, and why they differ in three places.
A good habit even now: keep models in a separate package, for example app.model or tracker.model. Then your files will look predictable: Expense.kt, AppState.kt, and in each — one main type.
Also, when a model lives separately, it’s much easier to notice: “aha, I added a new field — that means the data format changed.” This is useful even in a learning project.
6. Common mistakes when adding kotlinx.serialization
Error No. 1: added the dependency but forgot the serialization plugin.
A very common scenario: you added implementation("...kotlinx-serialization-json..."), wrote @Serializable, but the IDE still complains or User.serializer() can’t be found. That’s because without kotlin("plugin.serialization") the compiler does not generate serializers — the library alone can’t carry the whole process. Fix it by adding the plugin and syncing Gradle.
Error No. 2: the Kotlin plugin version and the serialization plugin version don’t match.
The painful part is that the error may look “unrelated”: sometimes it’s weird compiler messages or a build failure at a step that isn’t tied to your code. The practical rule is simple: if the project is on Kotlin 2.3.x, then kotlin("plugin.serialization") must also be 2.3.x.
Error No. 3: serializing a class that has a field of a complex type not supported out of the box.
For example, you added a field of type File, Path, Instant, or some custom class of yours without @Serializable. The compiler will say: “I don’t know how to serialize this.” It’s not being picky: serialization must have a clear algorithm for each field. At the start, keep models simple: numbers, strings, lists, nullable. Complex types are either wrapped into a simpler representation, or require a separate approach (but that’s not today’s topic).
Error No. 4: imported the wrong Serializable.
In the Kotlin/Java world there are several Serializable types. We need exactly kotlinx.serialization.Serializable. If you accidentally imported java.io.Serializable, the serialization compiler plugin won’t “see” it, and then you get riddles like “why doesn’t it work, I wrote Serializable”. Check the import — it’s small, but one of the most devious issues.
Error No. 5: expecting @Serializable to automatically start saving data to a file.
The annotation makes a class “eligible for serialization”, but it doesn’t write anything by itself. Writing/reading JSON is a separate step: the Json codec, encode/decode functions, and file operations. Today we lay the foundation (models + setup), and the practical pipeline “object ↔ JSON ↔ file” will be the next stage.
GO TO FULL VERSION