Introduction to Working with JSON in Kotlin
JSON (JavaScript Object Notation) is one of the most popular formats for data exchange between a server and a client. In modern Kotlin development, whether it's Android applications or server-side projects, the ability to work efficiently with JSON is an essential skill. In this article, we will thoroughly examine how to perform JSON parsing and serialization in Kotlin using the most popular libraries: kotlinx.serialization and Gson.
Whether you are creating a REST API, processing responses from external services, or saving local settings, understanding the principles of working with JSON will help you write cleaner and more efficient code.
Basics of JSON Parsing in Kotlin
What are Serialization and Deserialization?
Before moving to the code, it is important to understand two key concepts:
- Serialization — converting a Kotlin object (data class, list, etc.) into a JSON string.
- Deserialization (Parsing) — the reverse process: creating a Kotlin object from a JSON string.
Kotlin does not have built-in JSON support, so we use third-party libraries. Let's look at the two most popular ones.
The kotlinx.serialization Library
kotlinx.serialization is an official library from JetBrains that integrates perfectly with the Kotlin language. It works at compile time, ensuring high performance and type safety.
Adding the Library
First, 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.2")}Defining the Data Model
Let's create a class to represent a user:
import kotlinx.serialization.Serializable
@Serializabledata class User( val name: String, val age: Int, val email: String? = null, // nullable field val roles: List<String> = emptyList())The @Serializable annotation tells the compiler that this class can be serialized.
Serialization (Object → JSON)
import kotlinx.serialization.encodeToStringimport kotlinx.serialization.json.Json
fun main() { val user = User( name = "Anna", age = 28, email = "anna@example.com", roles = listOf("admin", "user") )
val jsonString = Json.encodeToString(user) println(jsonString) // {"name":"Anna","age":28,"email":"anna@example.com","roles":["admin","user"]}}Deserialization (JSON → Object)
import kotlinx.serialization.decodeFromString
fun main() { val json = """{"name":"Ivan","age":35,"roles":["user"]}""" val user = Json.decodeFromString<User>(json) println(user.name) // Ivan println(user.email) // null (not specified in JSON)}Configuring Json Settings
You can customize the parser's behavior:
val json = Json { prettyPrint = true // pretty formatting ignoreUnknownKeys = true // ignore extra fields in JSON isLenient = true // allow lenient parsing (e.g., quotes)}
val user = json.decodeFromString<User>(jsonString)The Gson Library
Gson from Google is another popular library, especially common in Android development.
Adding Gson
dependencies { implementation("com.google.code.gson:gson:2.10.1")}Usage Example
import com.google.gson.Gson
data class Product( val id: Int, val title: String, val price: Double)
fun main() { val gson = Gson() val product = Product(1, "Laptop", 999.99) // Serialization val json = gson.toJson(product) println(json) // {"id":1,"title":"Laptop","price":999.99} // Deserialization val jsonString = """{"id":2,"title":"Mouse","price":25.50}""" val parsedProduct = gson.fromJson(jsonString, Product::class.java) println(parsedProduct.title) // Mouse}