Ktor 1.6.4 Help

kotlinx.serialization

ContentNegotiation allows you to use content converters provided by the kotlinx.serialization library. This library supports JSON, CBOR, ProtoBuf, and other formats.

Add dependencies

Before registering a required converter, perform the following steps:

  1. Add the Kotlin serialization plugin, as described in the Setup section.

  2. Include the following artifacts in the build script:

    implementation "io.ktor:ktor-serialization:$ktor_version"
    implementation("io.ktor:ktor-serialization:$ktor_version")
    <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-serialization</artifactId> <version>${ktor_version}</version> </dependency>

    This will be enough for converting JSON.

  3. (Optional) To convert other formats (for example, CBOR or ProtoBuf), you need to include a corresponding artifact. Learn more from the Formats section.

Register a converter

Register the JSON converter

To register the JSON converter in your application, call the json method:

import io.ktor.serialization.* install(ContentNegotiation) { json() }

Inside the json method, you can access the JsonBuilder API, for example:

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

To learn how to receive and send data, see Receive and send data.

Register an arbitrary converter

To register an arbitrary converter from the kotlinx.serialization library (such as Protobuf or CBOR), call the serialization method and pass two parameters:

  • The required ContentType value.

  • An object of the class implementing the required encoder/decoder.

For example, you can register the Cbor converter in the following way:

install(ContentNegotiation) { serialization(ContentType.Application.Cbor, Cbor.Default) }
Last modified: 09 September 2021