Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 38 ยท Plugins and Serialization

Content Negotiation and JSON

Send and receive JSON in Ktor: install ContentNegotiation, annotate data classes with @Serializable, configure Json, and see how the Accept header picks a format.

Modern APIs speak JSON. In Ktor you do not build JSON strings by hand: you respond with a Kotlin object and receive one, and the ContentNegotiation plugin converts between objects and bytes. It also picks the format by looking at the request's Accept and Content-Type headers, which is where the name comes from. This lesson sets it up with kotlinx.serialization, covers the options you will actually change, and includes a runnable stand-in that implements JSON encoding, parsing and Accept negotiation.

Setup

Dependencies (in build.gradle.kts):

Kotlin
plugins {
    kotlin("plugin.serialization") version "2.2.0"
}
dependencies {
    implementation("io.ktor:ktor-server-content-negotiation")
    implementation("io.ktor:ktor-serialization-kotlinx-json")
}

Install the plugin and register JSON:

Kotlin
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.plugins.contentnegotiation.*
import kotlinx.serialization.Serializable

@Serializable
data class Book(val id: Int, val title: String, val author: String, val year: Int? = null)

@Serializable
data class NewBook(val title: String, val author: String, val year: Int? = null)

fun Application.module() {
    install(ContentNegotiation) {
        json()
    }
    routing {
        get("/books/{id}") {
            call.respond(Book(1, "The Kotlin Way", "Ann Lee"))   // becomes JSON
        }
        post("/books") {
            val input = call.receive<NewBook>()                  // parsed from JSON
            call.respond(HttpStatusCode.Created, Book(2, input.title, input.author, input.year))
        }
    }
}

A request GET /books/1 returns Content-Type: application/json and:

TEXT
{"id":1,"title":"The Kotlin Way","author":"Ann Lee"}

Notice that year is missing: its default is null and the standard Json configuration does not encode default values. A client can still send it. The classes must be annotated @Serializable; the compiler plugin then generates the serializer, so there is no reflection at runtime. The basics are covered in kotlinx.serialization basics.

Configuring Json

You pass a configured Json instance to control details:

Kotlin
install(ContentNegotiation) {
    json(Json {
        prettyPrint = true            // readable output (development only)
        ignoreUnknownKeys = true      // do not fail on fields we do not model
        encodeDefaults = true         // write default values too
        isLenient = false             // keep JSON strict
        explicitNulls = false         // omit null fields
    })
}

The two most important options for an API:

  • ignoreUnknownKeys = true makes your server tolerant: clients can add fields without breaking you. The default (strict) rejects unknown keys with a 400, which is safer if you want to catch typos.
  • explicitNulls = false drops null fields from output and treats a missing field as null on input.

What receive does with bad input

If the body is not valid JSON, is missing a required field or has the wrong type, receive<NewBook>() throws ContentTransformationException (a BadRequestException). Left alone, that becomes an error response; with the Status Pages plugin you answer with a tidy JSON error. A missing Content-Type: application/json header gives 415 Unsupported Media Type.

Negotiation

register several formats and Ktor chooses by the client's Accept header, trying the highest quality first:

Kotlin
install(ContentNegotiation) {
    json()
    xml()                       // ktor-serialization-kotlinx-xml
    // register(ContentType.Application.Cbor, ...)
}
  • Accept: application/json gets JSON; Accept: application/xml gets XML; Accept: */* gets the first registered converter.
  • Accept: image/png (a type you cannot produce) produces 406 Not Acceptable.
  • For incoming bodies the Content-Type header selects the converter.

Stand-in: JSON by hand, plus Accept negotiation

kotlinx.serialization generates code per class at compile time, and the runner cannot use compiler plugins. The stand-in below does the same job by hand, with a tiny JSON writer, a parser and a negotiator that picks a format from the Accept header. Read it to understand what the real converter does for you.

Kotlin Stand-in: JSON encode, decode and Accept negotiation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Practical tips

  • Never expose your database entities directly. Use separate request and response classes (NewBook versus Book) so a client cannot set an id or role it should not.
  • Use @SerialName("created_at") to map Kotlin names to a snake_case wire format.
  • Dates need a serializer: use kotlinx-datetime types or write a small custom KSerializer for java.time.
  • Return lists of objects as the top-level JSON for collections; consider wrapping with paging metadata for large result sets.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which annotation must a data class have to be (de)serialized with kotlinx.serialization?

    The compiler plugin generates the serializer for @Serializable classes.
  2. 2. What does ignoreUnknownKeys = true change?

    Without it, an unknown field in the JSON makes decoding fail.
  3. 3. A client sends Accept: image/png but only JSON and XML are registered. What is the correct outcome?

    The server cannot produce an acceptable representation, so 406.
  4. 4. Why use separate NewBook and Book classes?

    Separate input and output models avoid mass-assignment problems.

Summary

  • Install ContentNegotiation with json(); respond objects and receive<T>() bodies.
  • Mark classes @Serializable; configure Json { ... } for strictness, nulls and defaults.
  • Bad bodies throw exceptions that you should turn into 400/415 responses.
  • The Accept header selects the response format; unsupported formats give 406.
  • Use separate input and output models.

Next: Status Pages and Error Handling