Being still new to Kotlin and Ktor, I have run int...
# ktor
v
Being still new to Kotlin and Ktor, I have run into the following dilemma: Ktor exposes a
Cookie
data class like so:
Copy code
public data class Cookie(
    val name: String,
    val value: String,
    val encoding: CookieEncoding = CookieEncoding.URI_ENCODING,
    @get:JvmName("getMaxAgeInt")
    val maxAge: Int = 0,
    val expires: GMTDate? = null,
    val domain: String? = null,
    val path: String? = null,
    val secure: Boolean = false,
    val httpOnly: Boolean = false,
    val extensions: Map<String, String?> = emptyMap()
)
I would like to be able to (de)serialize this
Cookie
, however the library provided data class lacks the necessary annotation. So I am guessing the solution would be to take the publicly exposed
Cookie
data class and apply the serialization annotation inside my project. What would be the most idiomatic way to achieve this?
c
v
Very useful article, thank you
However, I am not sure if the following is possible in my case? We bind the
ColorSerializer
serializer to the
Color
class.
Copy code
@Serializable(with = ColorSerializer::class)
class Color(val rgb: Int)
As I am not going to be able to annotate the Cookie class that way
c
No, you create a
CookieSurrogate
that is annotated an assign the values inside it’s
deserialize
/
serialize
to the
Cookie
class
Copy code
@Serializable
@SerialName("Cookie")
private class CookieSurrogate(val name: String,
    val value: String)


object CookieSerializer : KSerializer<Cookie> {
    override val descriptor: SerialDescriptor = CookieSurrogate.serializer().descriptor

    override fun serialize(encoder: Encoder, value: Cookie) {
        val surrogate = CookieSurrogate(name = value.name, value = value.value)
        encoder.encodeSerializableValue(CookieSurrogate.serializer(), surrogate)
    }

    override fun deserialize(decoder: Decoder): Cookie {
        val surrogate = decoder.decodeSerializableValue(Cookie.serializer())
        return Cookie(name = surrogate.name, value = surrogate.value)
    }
}
simplyfied example
and you then pass the
CookieSerializer
to the
Json.endodeToString(CookieSerializer, cookie)
statring with this headline you can see how to apply the serializer in different ways https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#passing-a-serializer-manually
a
Ktor has functions for parsing and rendering cookies, which can be used instead of an explicit serializer/deserializer.
v
Christian, your answer was very thorough and using your example I manage to get the thing to compile. Thank you!
Aleksei, could you kindly link the mentioned functions, please?
a
Starting from this line, you can find the
parseServerSetCookieHeader
and
parseClientCookiesHeader
methods for parsing cookies, and the
renderSetCookieHeader
and
renderCookieHeader
methods for rendering them.