Introduction: Why JSON is the Foundation of Modern Kotlin Development
JSON (JavaScript Object Notation) remains the de facto standard for data exchange between server and client, whether it's a mobile Android app or a Ktor backend. In the Kotlin ecosystem, working with JSON is especially convenient thanks to the language's strong typing and powerful serialization libraries. In this article, we'll cover two main approaches: using the official kotlinx.serialization library and the popular Gson. You'll learn how to parse complex structures, serialize objects, and handle exceptions in practice.
Project Setup and Adding Dependencies
Before writing code, you need to add the libraries to the build.gradle.kts file (for Gradle). Let's look at both options.
Option 1: kotlinx.serialization (recommended)
- Add the plugin to
plugins:kotlin("plugin.serialization") version "1.9.22" - In
dependencies, add:implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.2")
Option 2: Gson (for compatibility with Java projects)
- In
dependencies, add:implementation("com.google.code.gson:gson:2.10.1")
// build.gradle.kts — full example for kotlinx.serializationplugins { kotlin("jvm") version "1.9.22" kotlin("plugin.serialization") version "1.9.22"}
dependencies { implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.2")}Parsing JSON in Kotlin: From Simple to Complex
Parsing (deserialization) is the process of converting a JSON string into a Kotlin object. Let's look at an example using user data.
Sample Data
{ "id": 123, "name": "Anna", "email": "anna@example.com", "active": true}Creating a Data Class
The same class is used for both libraries. Important: for kotlinx.serialization, you need to add the @Serializable annotation.
import kotlinx.serialization.Serializable
@Serializabledata class User( val id: Int, val name: String, val email: String, val active: Boolean)Parsing with kotlinx.serialization
import kotlinx.serialization.json.Json
fun parseWithKotlinx(jsonString: String): User { val json = Json { ignoreUnknownKeys = true } // ignore unknown fields return json.decodeFromString<User>(jsonString)}
// Usage:fun main() { val json = """{"id":123,"name":"Anna","email":"anna@example.com","active":true}""" val user = parseWithKotlinx(json) println(user.name) // Anna}Parsing with Gson
import com.google.gson.Gson
fun parseWithGson(jsonString: String): User { val gson = Gson() return gson.fromJson(jsonString, User::class.java)}
// Usage:fun main() { val json = """{"id":123,"name":"Anna","email":"anna@example.com","active":true}""" val user = parseWithGson(json) println(user.email) // anna@example.com}Serialization: Converting an Object to JSON
The reverse process — creating a JSON string from an object — is equally important for sending data to the server.
Serialization with kotlinx.serialization
import kotlinx.serialization.encodeToString
fun serializeWithKotlinx(user: User): String { val json = Json { prettyPrint = true } return json.encodeToString(user)}
// Result:// {// "id": 123,// "name": "Anna",// "email": "anna@example.com",// "active": true// }Serialization with Gson
fun serializeWithGson(user: User): String { val gson = GsonBuilder().setPrettyPrinting().create() return gson.toJson(user)}<