Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
163: kotlinx.serialization Basics
How do I actually turn a Kotlin object into JSON (and back)?
If you've used libraries like Gson or Moshi in the past, you're used to reflection doing the heavy lifting at runtime. kotlinx.serialization is different. It uses a compiler plugin to generate the serialization logic at compile time, which makes it faster and much friendlier for Kotlin Multiplatform projects.
The magic starts with the @Serializable annotation. Without it, the compiler won't generate the necessary "serializer" for your class, and you'll get a runtime exception. Let's say we're building a game and need to save a character's state:
import kotlinx.serialization.*
import kotlinx.serialization.json.*
@Serializable
data class GameCharacter(
val name: String,
val level: Int,
val inventory: List<String>
)
fun main() {
val hero = GameCharacter("Althea", 12, listOf("Iron Sword", "Health Potion"))
// Object to JSON string
val jsonString = Json.encodeToString(hero)
println(jsonString) // {"name":"Althea","level":12,"inventory":["Iron Sword","Health Potion"]}
// JSON string back to Object
val decodedHero = Json.decodeFromString<GameCharacter>(jsonString)
println(decodedHero.name)
}
I usually recommend sticking to the Json singleton for basic tasks, but keep in mind you can create a custom Json { ... } configuration if you need to tweak how the parser behaves.
What if the API uses snake_case but I want camelCase in my code?
This is one of the most common friction points when dealing with external APIs. You don't want to name your Kotlin properties user_account_id just to satisfy a JSON response; that violates every Kotlin style guide we have.
The solution is the @SerialName annotation. It acts as a bridge, telling the library "When you see this key in the JSON, map it to this specific property in my class."
@Serializable
data class UserProfile(
@SerialName("user_id")
val userId: Int,
@SerialName("full_name")
val fullName: String,
val email: String // This matches the JSON key "email" exactly
)
I love this approach because it keeps your domain models clean while remaining flexible enough to handle whatever messy naming conventions the backend team decided to use.
How do I stop the app from crashing when a field is missing from the JSON?
By default, kotlinx.serialization is strict. If the JSON is missing a field that your data class requires, it'll throw a SerializationException. In the real world, APIs are rarely that consistent.
The simplest fix is to provide a default value in your data class. If the library doesn't find the key in the JSON, it will just fall back to that default. However, there is a catch: you have to tell the Json configuration to actually use those defaults.
@Serializable
data class GameSettings(
val volume: Float = 1.0f,
val darkMode: Boolean = true
)
val jsonConfig = Json {
encodeDefaults = true
ignoreUnknownKeys = true // Essential if the API sends extra data you don't need
}
fun main() {
// Imagine the JSON only contains "volume"
val rawJson = """{"volume": 0.5}"""
// Because we provided a default for darkMode, this won't crash
val settings = jsonConfig.decodeFromString<GameSettings>(rawJson)
println(settings.darkMode) // true
}
Pro tip: Always set ignoreUnknownKeys = true in your production configurations. APIs evolve, and the last thing you want is for your app to crash simply because the backend added a new last_login_timestamp field that you aren't even using yet.
📋 Practical Task
Exercise: Build a Movie Library Parser
You are building a movie catalog app. You receive a JSON string from a mock API, but the API uses snake_case and sometimes forgets to include the "rating" field.
Your Task:
- Create a data class named
Moviemarked as@Serializable. - The class should have three properties:
title(String),releaseYear(Int), andrating(Double). - Use
@SerialNameto maprelease_yearfrom JSON toreleaseYear. - Give
ratinga default value of0.0so the app doesn't crash if it's missing. - Configure a
Jsoninstance toignoreUnknownKeys = true. - Write a main function that decodes the following JSON string into a
Movieobject and prints the result:"{"title": "Inception", "release_year": 2010, "genre": "Sci-Fi", "extra_info": "Dream within a dream"}"
Note: The JSON contains "genre" and "extra_info" which are not in your class, so your configuration must handle those without crashing.
There are no comments for now.