0Pricing
Kotlin Academy · Lesson

Content Negotiation and kotlinx.serialization

Configure JSON serialization and deserialize request bodies automatically.

Content Negotiation and kotlinx.serialization is a free Kotlin Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is Content Negotiation?

Content negotiation is the HTTP mechanism by which a client and server agree on the format of the response body. The client sends an Accept header; the server picks the best matching format. Ktor's ContentNegotiation plugin automates this.

Adding Dependencies

Add the ContentNegotiation plugin and the kotlinx.serialization JSON converter:

dependencies {
    implementation("io.ktor:ktor-server-content-negotiation:2.3.12")
    implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.12")
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.1")
}

Installing ContentNegotiation

Install the plugin in an Application module and register the JSON converter:

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

fun Application.configureSerialization() {
    install(ContentNegotiation) {
        json()
    }
}

@Serializable Data Classes

Annotate your data classes with @Serializable from kotlinx.serialization. The Kotlin compiler plugin generates the serializer at compile time — no reflection needed at runtime:

import kotlinx.serialization.Serializable

@Serializable
data class User(val id: Long, val name: String, val email: String)

Responding with a Serializable Object

Once ContentNegotiation is installed, pass any @Serializable object to call.respond(). Ktor serializes it to JSON automatically:

get("/users/{id}") {
    val user = User(1L, "Alice", "alice@example.com")
    call.respond(user)  // serialized to JSON
}

Receiving a Serializable Object

Use call.receive() to deserialize the request body into a @Serializable class. If the body is malformed, Ktor throws a ContentTransformationException:

post("/users") {
    val newUser = call.receive<User>()
    call.respond(HttpStatusCode.Created, newUser)
}

Customizing the JSON Configuration

Pass a Json instance to json() to customize serialization: ignore unknown keys, pretty-print, use lenient mode, etc.:

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

Multiple Content Types

Register multiple converters to support different Accept types. Ktor picks the first that matches the client's Accept header:

install(ContentNegotiation) {
    json()
    // xml() with ktor-serialization-kotlinx-xml if needed
}

Serializing Lists and Maps

Wrap collections in a response object or use call.respond(list) directly. kotlinx.serialization handles List, Map, and nested generics as long as the element types are @Serializable:

get("/users") {
    val users = listOf(
        User(1, "Alice", "a@example.com"),
        User(2, "Bob", "b@example.com")
    )
    call.respond(users)
}

Custom Serializers

For types you don't own (e.g., java.time.Instant), implement a KSerializer and register it via @Serializable(with = MySerializer::class) or a contextual serializer module:

val module = SerializersModule {
    contextual(Instant::class, InstantSerializer)
}
install(ContentNegotiation) {
    json(Json { serializersModule = module })
}

Error Handling for Deserialization Failures

Install the StatusPages plugin to return a clean error response when call.receive() fails:

install(StatusPages) {
    exception<ContentTransformationException> { call, _ ->
        call.respond(HttpStatusCode.BadRequest, "Invalid request body")
    }
}

Quick Check

Which annotation is required on a Kotlin data class to make it serializable by kotlinx.serialization?

Recap: Content Negotiation and kotlinx.serialization

Key takeaways:

  • Install ContentNegotiation + json() for automatic JSON serialization/deserialization
  • Annotate data classes with @Serializable
  • Use call.respond(obj) to serialize and call.receive() to deserialize
  • Customize with a Json { ... } instance passed to json()
  • Use StatusPages to handle deserialization errors gracefully

Frequently asked questions

Is the “Content Negotiation and kotlinx.serialization” lesson free?

Yes — the full text of “Content Negotiation and kotlinx.serialization” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.

What will I learn in “Content Negotiation and kotlinx.serialization”?

Configure JSON serialization and deserialize request bodies automatically. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Content Negotiation and kotlinx.serialization” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Ktor Project Setup: embeddedServer and Application Modules
  2. Routing and Typed Parameters
  3. Content Negotiation and kotlinx.serialization
  4. Authentication Plugins: JWT and Session
← Back to Kotlin Academy