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
Accept
andContent-Type
headers.Serializing/deserializing the content in the specific format, which is provided by either the built-in
kotlinx.serialization
library or external ones, such asGson
andJackson
, amongst others.
Install ContentNegotiation
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 application/json
and application/xml
data:
Built-in converters
Ktor provides the set of built-in converters for handing various content types without writing your own logic:
kotlinx.serialization for JSON, Protobuf, CBOR, and so on
Gson for JSON
Jackson for JSON
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 @Serializable
annotation:
Receive data
To receive and convert a content for a request, call the receive method that accepts a data class as a parameter:
The 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.
Send data
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. You can find the full example here: json-kotlinx.
Implement a custom converter
In Ktor, you can write your own converter for serializing/deserializing data. To do this, you need to implement the ContentConverter interface:
Take a look at the GsonConverter class as an implementation example.