JSON support using kotlinx.serialization

Estimated reading time: 1 minute

The SerializationConverter feature allows you to handle JSON content in your application easily using kotlinx.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:

install(ContentNegotiation) {
    serialization()
}

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:

install(ContentNegotiation) {
    serialization(
        contentType = ContentType.Application.Json,
        json = Json(
            DefaultJsonConfiguration.copy(
                prettyPrint = true
            )
        )
    )
}