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:

    kotlinx.serialization - 图1

    Gradle (Groovy)

    Gradle (Kotlin)

    Maven

    kotlinx.serialization - 图2

    1. implementation "io.ktor:ktor-serialization:$ktor_version"
  1. This will be enough for converting JSON.
  1. (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:

  1. import io.ktor.serialization.*
  2. install(ContentNegotiation) {
  3. json()
  4. }

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

  1. install(ContentNegotiation) {
  2. json(Json {
  3. prettyPrint = true
  4. isLenient = true
  5. // ...
  6. })
  7. }

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:

  1. install(ContentNegotiation) {
  2. serialization(ContentType.Application.Cbor, Cbor.Default)
  3. }