JSON support using kotlinx.serialization

The SerializationConverter feature allows you to handle JSON content in your application easily usingkotlinx.serialization library.

This feature is a ContentNegotiation converter.

This feature is defined in the class io.ktor.serialization.SerializationConverter in the artifact io.ktor:ktor-serialization:$ktor_version.

dependencies { implementation "io.ktor:ktor-serialization:$ktor_version"}

dependencies { implementation("io.ktor:ktor-serialization:$ktor_version")}

<project> … <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-serialization</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies></project>

Basic usage

To install the feature by registering a JSON content convertor using kotlinx.serialization:

  1. install(ContentNegotiation) {
  2. serialization()
  3. }

Configuration

The serialization() function has two optional parameters with default arguments:

  • contentType provides a way to specify which content types it should handle, ContentType.Application.Json by default.
  • json provides ability to configure JSON formatter, Json(DefaultJsonConfiguration) by default.

Advanced example:

  1. install(ContentNegotiation) {
  2. serialization(
  3. contentType = ContentType.Application.Json,
  4. json = Json(
  5. DefaultJsonConfiguration.copy(
  6. prettyPrint = true
  7. )
  8. )
  9. )
  10. }