Session Serializers

Serializers

You can specify a custom serializer with:

  1. application.install(Sessions) {
  2. cookie<MySession>("SESSION") {
  3. serializer = MyCustomSerializer()
  4. }
  5. }

If you do not specify any serializer, it will use one with an internal optimized format.

SessionSerializerReflection

This is the default serializer, when no serializer is specified:

  1. cookie<MySession>("SESSION") {
  2. serializer = autoSerializerOf()
  3. }

Custom serializers

The Sessions API provides a SessionSerializer interface, that looks like this:

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

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

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

So for example you can create a JSON session serializer using Gson:

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

And configuring it:

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