Content negotiation and serialization
The ContentNegotiation 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 feature, pass it to the
install function in the application initialization code. This can be the
main function ...
... 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:
To pass a data object in a response, you can use the respond method:
In this case, Ktor uses the
Accept header to choose the required converter.
Implement a custom converter
Take a look at the GsonConverter class as an implementation example.