Serializers

Sessions allow you to choose whether to pass the entire payload between the client and server or store session data on the server and pass only a session ID. In both cases, Ktor uses the default serializer to serialize session data. You can also provide your own custom serializer and, for example, convert session data to JSON.

Default Serializer

The default session serializer is used when no serializer is specified explicitly and constructed with defaultSessionSerializer function. It has no configuration and uses the text format. Unlike general purpose serializers, it is optimized for size to produce short one-line serialized strings.

Limitations

The default session serializer has the following limitations:

  • Session class should be a regular or sealed class.

  • Polymorphic serialization is limited to only sealed classes: abstract classes are not allowed.

  • Properties of a session class should have one of the following types:

    • primitive types;

    • String;

    • enum class;

    • collection classes such as List, Set, Map;

    • data class;

    • sealed class;

    • object;

  • Type parameters of collections should be primitive or String.

  • Inner classes are not supported.

  • Cyclic object graphs are not supported.

Text Format

The default serializer converts data into a form-url-encoded bundle where names are properties and values are encoded with a type prefix starting with a # hash character. The character following the hash character points to a value type. For example, a data class with a single integer property is encoded to test=#i1.

Custom Serializers

The Sessions API provides the SessionSerializer interface that looks like this:

  1. interface SessionSerializer<T> {
  2. fun serialize(session: T): String
  3. fun deserialize(text: String): T
  4. }

This interface is for a generic serializer, and you can install it like this:

  1. cookie<MySession>("NAME") {
  2. serializer = MyCustomSerializer()
  3. }

For example, you can create a JSON session serializer using Gson

  1. class GsonSessionSerializer<T>(
  2. val type: java.lang.reflect.Type,
  3. val gson: Gson = Gson(),
  4. configure: Gson.() -> Unit = {}
  5. ) : SessionSerializer<T> {
  6. init {
  7. configure(gson)
  8. }
  9. override fun serialize(session: T): String = gson.toJson(session)
  10. override fun deserialize(text: String): T = gson.fromJson(text, type) as T
  11. }

…and configure it:

  1. cookie<MySession>("NAME") {
  2. serializer = GsonSessionSerializer(MySession::class.java)
  3. }