kotlinx.serialization Library for JSON Processing in Kotlin

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?

Kotlinx.serialization is the official Kotlin library for data serialization and deserialization, including the JSON format. It provides a powerful and type-safe way to convert Kotlin objects to and from JSON, without using reflection and with multiplatform support (JVM, JS, Native).

Why is JSON processing needed in Kotlin?

In modern Kotlin development (Android, server applications on Ktor, multiplatform projects), working with JSON is a mandatory task: data exchange with REST APIs, configuration files, data storage. Kotlinx.serialization solves this efficiently, safely, and with minimal boilerplate code.

Installation

To use the library, add the plugin to build.gradle.kts:

plugins {    kotlin("plugin.serialization") version "1.9.22"}

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

For Maven, add the dependency and the kotlin-maven-plugin with serialization configuration.

Main Features

  • @Serializable — annotation for classes that need to be serialized.
  • Json.encodeToString() — converts an object to a JSON string.
  • Json.decodeFromString() — parses a JSON string into an object.
  • JsonObject / JsonElement — dynamic work with JSON without creating DTOs.
  • @Transient, @Required, @SerialName — fine-tuning of fields.
  • JsonConfiguration — formatting settings (prettyPrint, ignoreUnknownKeys).

Kotlin Code Example

import kotlinx.serialization.*import kotlinx.serialization.json.*

@Serializabledata class User(val name: String, val age: Int)

fun main() { val user = User("Alice", 30) // Serialization val jsonString = Json.encodeToString(user) println(jsonString) // {"name":"Alice","age":30} // Deserialization val decodedUser = Json.decodeFromString<User>(jsonString) println(decodedUser) // User(name=Alice, age=30) // Working with dynamic JSON val jsonObject = Json.parseToJsonElement("""{"city":"Moscow","zip":101000}""").jsonObject println(jsonObject["city"]) // "Moscow"}

When to Use

The library is ideal for:

  • Android applications (Retrofit + kotlinx.serialization).
  • Server projects on Ktor.
  • Multiplatform applications (KMP).
  • Any projects where fast and safe JSON handling without reflection is needed.

It surpasses Gson and Jackson in performance and type safety, especially in Kotlin projects.

Recommendations