WebSockets serialization
Similar to the ContentNegotiation plugin, WebSockets allow you to serialize/deserialize text frames in a specific format. The Ktor client supports the following formats out-of-the-box: JSON, XML, CBOR, and ProtoBuf.
Add dependencies
Before using kotlinx.serialization converters, you need to add the Kotlin serialization plugin as described in the Setup section.
JSON
To serialize/deserialize JSON data, you can choose one of the following libraries: kotlinx.serialization, Gson, or Jackson.
Add the ktor-serialization-kotlinx-json
artifact in the build script:
Add the ktor-serialization-gson
artifact in the build script:
Add the ktor-serialization-jackson
artifact in the build script:
XML
To serialize/deserialize XML, add the ktor-serialization-kotlinx-xml
in the build script:
Note that XML serialization is supported on JVM only.
CBOR
To serialize/deserialize CBOR, add the ktor-serialization-kotlinx-cbor
in the build script:
ProtoBuf
To serialize/deserialize ProtoBuf, add the ktor-serialization-kotlinx-protobuf
in the build script:
Configure a serializer
JSON serializer
To register the JSON serializer in the WebSockets configuration, create a KotlinxWebsocketSerializationConverter
instance with the Json
parameter and assign this instance to the contentConverter
property:
To register the Gson serializer, assign GsonWebsocketContentConverter
to the contentConverter
property:
To register the Jackson serializer, assign JacksonWebsocketContentConverter
to the contentConverter
property:
XML serializer
To register the XML serializer in the WebSockets configuration, create a KotlinxWebsocketSerializationConverter
instance with the XML
parameter and assign this instance to the contentConverter
property:
CBOR serializer
To register the CBOR serializer in the WebSockets configuration, create a KotlinxWebsocketSerializationConverter
instance with the Cbor
parameter and assign this instance to the contentConverter
property:
ProtoBuf serializer
To register the ProtoBuf serializer in the WebSockets configuration, create a KotlinxWebsocketSerializationConverter
instance with the ProtoBuf
parameter and assign this instance to the contentConverter
property:
Receive and send data
Create a data class
To serialize/deserialize text frames into/from 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:
To learn more about kotlinx.serialization
, see the Kotlin Serialization Guide.
Send data
To send a class instance within a text frame in a specified format, use the sendSerialized
function:
Receive data
To receive and convert a content of a text frame, call the receiveDeserialized
function that accepts a data class as a parameter:
To receive deserialized frames from the incoming channel, use the WebsocketContentConverter.deserialize function. WebsocketContentConverter
is available via the DefaultClientWebSocketSession.converter
property.