Working with JSON in Kotlin: Parsing and Serialization for Beginners

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

Introduction: Why Kotlin Works with JSON?

\n\n

JSON (JavaScript Object Notation) is a lightweight data interchange format that has become the standard for modern web applications and APIs. If you write in Kotlin, whether it's an Android app or a server-side component, sooner or later you will need to parse JSON responses from a server or serialize your objects for sending.

\n\n

Kotlin is a modern language that runs on top of the JVM and is fully compatible with Java. However, Kotlin has its own powerful tools for working with JSON that make code more concise and safe. In this article, we will cover two of the most popular approaches: using the official kotlinx.serialization library and the time-tested Gson.

\n\n

This article is aimed at beginners. We will start with simple string parsing, then move on to creating complex nested structures, and finally touch on serialization — converting your objects back to JSON.

\n\n

1. Project Setup: Dependencies and Imports

\n\n

Before writing code, you need to add the libraries. We will cover two options.

\n\n

1.1. Installing kotlinx.serialization

\n\n

This is the official solution from JetBrains. Add the following to your build.gradle.kts file:

\n\n
plugins {\n    kotlin("jvm") version "1.9.0"\n    kotlin("plugin.serialization") version "1.9.0"\n}\n\ndependencies {\n    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")\n}\n
\n\n

1.2. Installing Gson

\n\n

Gson is a library from Google. It is simpler to set up but requires more manual work:

\n\n
dependencies {\n    implementation("com.google.code.gson:gson:2.10.1")\n}\n
\n\n

After syncing the project, you can start writing code.

\n\n

2. Parsing JSON in Kotlin with kotlinx.serialization

\n\n

This approach is the most "Kotlin-esque". You declare data classes and add the @Serializable annotation. The library will generate the parsing code itself.

\n\n

2.1. Simple Example: User Data

\n\n

Suppose we have a JSON string:

\n\n
{\n    "name": "Anna",\n    "age": 25,\n    "email": "anna@example.com"\n}\n
\n\n

Create the model:

\n\n
import kotlinx.serialization.Serializable\nimport kotlinx.serialization.json.Json\n\n@Serializable\ndata class User(\n    val name: String,\n    val age: Int,\n    val email: String\n)\n\nfun main() {\n    val jsonString = """\n        {\n            "name": "Anna",\n            "age": 25,\n            "email": "anna@example.com"\n        }\n    """.trimIndent()\n\n    val user = Json.decodeFromString<User>(jsonString)\n    println("Name: ${user.name}, Age: ${user.age}")\n}\n
\n\n

As you can see, no manual mappings — everything is automatic.

\n\n

2.2. Working with Lists and Nested Objects

\n\n

Real APIs often return arrays. Let's add an address field:

\n\n
@Serializable\ndata class Address(\n    val city: String,\n    val street: String\n)\n\n@Serializable\ndata class UserWithAddress(\n    val name: String,\n    val age: Int,\n    val address: Address\n)\n\nfun main() {\n    val jsonArray = """\n        [\n            {"name": "Ivan", "age": 30, "address": {"city": "Moscow", "street": "Tverskaya"}},\n            {"name": "Maria", "age": 22, "address": {"city": "SPb", "street": "Nevsky"}}\n        ]\n    """.trimIndent()\n\n    val users = Json.decodeFromString<List<UserWithAddress>>(jsonArray)\n    users.forEach { println("${it.name} lives in ${it.address.city}") }\n}\n
\n\n

Note: to work with lists, the generic List<UserWithAddress> is used.

\n\n

3. Parsing JSON with Gson

\n\n

Gson is a classic Java library. It also works great in Kotlin, but requires a bit more code.

\n\n

3.1. Basic Parsing

\n\n
import com.google.gson.Gson\n\ndata cl                

Blogs

Book Recommendations