Content negotiation and serialization
The ContentNegotiation plugin (previously known as feature) serves two primary purposes:
Negotiating media types between the client and server. For this, it uses the
Serializing/deserializing the content in the specific format, which is provided by either the built-in
kotlinx.serializationlibrary or external ones, such as
Jackson, amongst others.
To install the
ContentNegotiation plugin, pass it to the
install function in the application initialization code. Depending on the way used to create a server, this can be the
embeddedServer function call ...
... or a specified module.
Register a converter
To register a converter for a specified
Content-Type, you need to call the register method. In the example below, two custom converters are registered to deserialize
Ktor provides the set of built-in converters for handing various content types without writing your own logic:
See a corresponding topic to learn how to install the required dependencies, register, and configure a converter.
Receive and send data
Create a data class
To deserialize received data into an object, you need to create a data class, for example:
If you use kotlinx.serialization, make sure that this class has the
To receive and convert a content for a request, call the receive method that accepts a data class as a parameter:
Content-Type of the request will be used to choose a converter for processing the request. The example below shows a sample HTTP client request containing JSON data that will be converted to a
Customer object on the server side:
You can find the full example here: json-kotlinx.
To pass a data object in a response, you can use the respond method:
Implement a custom converter
Take a look at the GsonConverter class as an implementation example.