Serialization (kotlinx) for Kotlin: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is kotlinx.serialization and why do you need it?



kotlinx.serialization is an official library from JetBrains for serialization and deserialization of data in Kotlin. It provides a powerful, type-safe, and multiplatform way to convert Kotlin objects into various formats (JSON, Protobuf, CBOR, YAML, and others) and back.



Main reasons to use this library:

  • Multiplatform: Works on JVM, JS, Native (iOS, Android, Desktop).
  • Type safety: Serialization is checked at compile time, eliminating runtime errors.
  • Performance: Uses reflection only when necessary (via compiler plugin).
  • Flexibility: Supports custom serializers, polymorphism, optional fields, and much more.
  • Integration with Kotlin: Fully leverages language features (data class, sealed class, null safety).


Installation and Setup



To use kotlinx.serialization, you need to add the compiler plugin and dependency to your project.



1. Adding the plugin (build.gradle.kts):

plugins {    kotlin("jvm") version "1.9.0" // or your Kotlin version    kotlin("plugin.serialization") version "1.9.0"}


2. Adding the dependency:

dependencies {    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.2")}


3. For Maven (pom.xml):

<plugin>    <groupId>org.jetbrains.kotlin</groupId>    <artifactId>kotlin-maven-plugin</artifactId>    <version>1.9.0</version>    <configuration>        <pluginOptions>            <option>plugin:org.jetbrains.kotlin.plugin.serialization</option>        </pluginOptions>    </configuration></plugin>

<dependency> <groupId>org.jetbrains.kotlinx</groupId> <artifactId>kotlinx-serialization-json</artifactId> <version>1.6.2</version></dependency>


Quick Start: First Example



import kotlinx.serialization.Serializableimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.encodeToStringimport kotlinx.serialization.decodeFromString

// 1. Define a serializable class@Serializabledata class User(val name: String, val age: Int, val email: String? = null)

fun main() { // 2. Create an object val user = User("Alice", 30, "alice@example.com")

// 3. Serialize to JSON val jsonString = Json.encodeToString(user) println("Serialized JSON: $jsonString")

// 4. Deserialize back val decodedUser = Json.decodeFromString<User>(jsonString) println("Deserialized object: $decodedUser")}


Output:

Serialized JSON: {"name":"Alice","age":30,"email":"alice@example.com"}Deserialized object: User(name=Alice, age=30, email=alice@example.com)


Main Methods and Functions (8+)



1. Json.encodeToString()

What it does: Serializes a Kotlin object to a JSON string.

Parameters:

  • value (T) — object to serialize.
  • serializer (Serializer<T>?) — optional custom serializer.
val user = User("Bob", 25)val json = Json.encodeToString(user)println(json) // {"name":"Bob","age":25}


2. Json.decodeFromString()

What it does: Deserializes a JSON string to a Kotlin object.

Parameters:

  • string (String) — JSON string.
  • des

Recommendations