JSON support using kotlinx.serialization

预计阅读时间: 2 分钟

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

This feature is a ContentNegotiation converter.

本特性在构件 io.ktor:ktor-serialization:$ktor_version 中的 io.ktor.serialization.SerializationConverter 类中定义
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) {


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) {
        contentType = ContentType.Application.Json,
        json = Json(
                prettyPrint = true