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:
Add the Kotlin serialization plugin, as described in the Setup section.
Include the following artifacts in the build script:
Gradle (Groovy)
Gradle (Kotlin)
Maven
implementation "io.ktor:ktor-serialization:$ktor_version"
This will be enough for converting JSON.
- (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)
}