2

I want to serializable following class using kotlinx-serializer.

enter image description here

But since it contains Map with custom types - HttpUrl & List<Cookie>,it gives an error

  1. Serializer has not been found for type 'HttpUrl'
  2. Serializer has not been found for type 'Cookie

When Looked into kotlinx serialization documentation it looks like I will need to create a custom KSerializer for the above map type. so I can add it like below.

@Serializable(with = CookieSerializer::class)
val cookies: Map<HttpUrl, List<Cookie>> = emptyMap()

I am looking into some inputs on how I can create a custom CookieSerializer, I tried using the following approach, just to see if compile time error is resolved.

@Serializer(forClass = Map::class)
object CookieSerializer : KSerializer<Map<HttpUrl, List<Cookie>>> {
    override val descriptor: SerialDescriptor =
        PrimitiveSerialDescriptor("Cookie", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: Map<HttpUrl, List<Cookie>>) {

    }

    override fun deserialize(decoder: Decoder): Map<HttpUrl, List<Cookie>> {
        return emptyMap()
    }
}

But I still receive an error.

enter image description here

Vipul
  • 27,808
  • 7
  • 60
  • 75

1 Answers1

2

The errors indicate that HttpUrl and Cookie are not serializable. If you control the source for these classes, you can make them serializable by applying @Serializable, just like you are making ApplicationConfiguration serializable here. Maps are by default serializable in kotlinx.serialization.

The code you specify here tries to serialize Map<HttpUrl, List<Cookie>> (as a whole) using CookieSerializer, which seems unnecessary. If you don't control the source of Cookie, you can specify a serializer to use as follows: val cookies: Map<HttpUrl, List<@Serializable(CookieSerializer::class) Cookie>> .

For information on how to write custom serializers, please refer to the full documentation. It's a bit more intricate than what you are trying to do here (which I recommend you not to do, but just fyi) when writing serializers for generic types, such as maps.

Steven Jeuris
  • 18,274
  • 9
  • 70
  • 161