Skip to Content
Course content

163: kotlinx.serialization Basics

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 Movie marked as @Serializable.
  • The class should have three properties: title (String), releaseYear (Int), and rating (Double).
  • Use @SerialName to map release_year from JSON to releaseYear.
  • Give rating a default value of 0.0 so the app doesn't crash if it's missing.
  • Configure a Json instance to ignoreUnknownKeys = true.
  • Write a main function that decodes the following JSON string into a Movie object 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.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.