Skip to Content
Course content

119: Ktor Content Negotiation and Serialization

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

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 install block and pass a configuration object to json():

install(ContentNegotiation) {
    json(kotlinx.serialization.json.Json {
        prettyPrint = true
        isLenient = true
        ignoreUnknownKeys = true
    })
}

I added ignoreUnknownKeys = true as 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.serialization will 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-serialization plugin and the ktor-server-content-negotiation and ktor-serialization-kotlinx-json dependencies.
  • Define a @Serializable data class called WeatherReport with the following fields: city (String), temperature (Double), condition (String), and humidity (Int).
  • Install the ContentNegotiation plugin and configure it to use JSON with prettyPrint = true.
  • Create a route /weather that responds with a WeatherReport object 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.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.