Vladimir
06/15/2024, 11:33 AMCookie
data class like so:
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?Chrimaeon
06/15/2024, 11:42 AMVladimir
06/15/2024, 12:04 PMVladimir
06/15/2024, 12:06 PMColorSerializer
serializer to the Color
class.
@Serializable(with = ColorSerializer::class)
class Color(val rgb: Int)
Vladimir
06/15/2024, 12:07 PMChrimaeon
06/15/2024, 12:09 PMCookieSurrogate
that is annotated an assign the values inside it’s deserialize
/ serialize
to the Cookie
classChrimaeon
06/15/2024, 12:13 PM@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 exampleChrimaeon
06/15/2024, 12:17 PMCookieSerializer
to the Json.endodeToString(CookieSerializer, cookie)
Chrimaeon
06/15/2024, 12:20 PMAleksei Tirman [JB]
06/15/2024, 4:57 PMVladimir
06/15/2024, 5:50 PMVladimir
06/15/2024, 5:50 PMAleksei Tirman [JB]
06/15/2024, 5:54 PMparseServerSetCookieHeader
and parseClientCookiesHeader
methods for parsing cookies, and the renderSetCookieHeader
and renderCookieHeader
methods for rendering them.