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
119: Ktor Content Negotiation and Serialization
Alright, so we've got our Ktor server up and running, and we can send back simple strings. But in the real world, nobody wants a raw string; they want JSON. I want to build a small endpoint for a book catalog that returns a specific book's details. Let's see what happens when we try to do this the "obvious" way.
The "It should just work" attempt
I'll start by defining a simple data class for a book and trying to return it directly from a route. I'm thinking, "Ktor is smart, it'll figure out how to turn this object into something the browser understands," right?
data class Book(val id: Int, val title: String, val author: String)
routing {
get("/book") {
val myBook = Book(1, "The Kotlin Guide", "Jane Doe")
call.respond(myBook)
}
}
If you run this, you're going to hit a wall immediately. The code won't even compile, or it'll throw a TransformationException at runtime. Why? Because Ktor has no idea what a Book is. To Ktor, it's just a random JVM object. It doesn't automatically assume you want JSON, XML, or some proprietary binary format. It needs a translator.
Bringing in the Content Negotiator
This is where ContentNegotiation comes in. Think of it as a diplomatic middleman. When a client sends a request, they usually include an Accept header (like Accept: application/json). The Content Negotiation plugin looks at that header and says, "Okay, the client wants JSON. Do I have a tool installed that knows how to turn Kotlin objects into JSON?"
First, I need to add the necessary dependencies to my build.gradle.kts. I'm using kotlinx.serialization because it's the official JetBrains way and it's incredibly fast.
implementation("io.ktor:ktor-server-content-negotiation-jvm:$ktor_version")
implementation("io.ktor:ktor-serialization-kotlinx-json-jvm:$ktor_version")
Now, I'll install the plugin in my server setup:
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.plugins.contentnegotiation.*
install(ContentNegotiation) {
json()
}
I've told Ktor: "If someone asks for JSON, use the kotlinx.serialization library to handle it." I'll try running the /book route again. But wait—it's still failing. I'm getting a SerializationException saying the class Book is not serializable.
The missing piece: The @Serializable annotation
This is a common "gotcha." Unlike some Java libraries (like Jackson) that use reflection to peek inside your classes at runtime, kotlinx.serialization generates the serialization logic at compile time. It doesn't just guess; it needs your explicit permission to be turned into JSON.
I just need to add the @Serializable annotation to my data class. I also need to make sure the serialization plugin is applied in my Gradle file: plugins { id("org.jetbrains.kotlin.plugin.serialization") version "..." }.
import kotlinx.serialization.Serializable
@Serializable
data class Book(val id: Int, val title: String, val author: String)
Now, when I hit localhost:8080/book, I finally see what I wanted:
{ "id": 1, "title": "The Kotlin Guide", "author": "Jane Doe" }Fine-tuning the output
One thing that bugs me about the default JSON output is that it's all bunched up on one line. It's great for the network, but a nightmare for me to read while debugging. I can actually configure the JSON serializer to be "pretty" during development.
I'll go back to my
installblock and pass a configuration object tojson():install(ContentNegotiation) { json(kotlinx.serialization.json.Json { prettyPrint = true isLenient = true ignoreUnknownKeys = true }) }I added
ignoreUnknownKeys = trueas well. I've found that when you start receiving JSON from external APIs, they often send extra fields you don't actually need. Without this setting,kotlinx.serializationwill throw an error the moment it sees a field that isn't in your data class. It's a lifesaver for API stability.
📋 Practical Task
Build a Weather Forecast JSON Endpoint
Create a Ktor server that provides a weather report. You will need to:
- Add the
kotlinx-serializationplugin and thektor-server-content-negotiationandktor-serialization-kotlinx-jsondependencies. - Define a
@Serializabledata class calledWeatherReportwith the following fields:city (String),temperature (Double),condition (String), andhumidity (Int). - Install the
ContentNegotiationplugin and configure it to use JSON withprettyPrint = true. - Create a route
/weatherthat responds with aWeatherReportobject containing sample data for your favorite city. - Verify that the response is valid, formatted JSON when accessed via your browser or a tool like Postman.
There are no comments for now.