I am using the content negotiation Ktor plugin whi...
# serialization
o
I am using the content negotiation Ktor plugin which uses Kotlinx serialization to serialize a set of serializable objects, but I am getting the exception:
Copy code
kotlinx.serialization.SerializationException: Class 'LinkedHashSet' is not registered for polymorphic serialization in the scope of 'Set'.
To be registered automatically, class 'LinkedHashSet' has to be '@Serializable', and the base class 'Set' has to be sealed and '@Serializable'.
Alternatively, register the serializer for 'LinkedHashSet' explicitly in a corresponding SerializersModule.
	at kotlinx.serialization.internal.AbstractPolymorphicSerializerKt.throwSubtypeNotRegistered(AbstractPolymorphicSerializer.kt:102)
	at kotlinx.serialization.internal.AbstractPolymorphicSerializerKt.throwSubtypeNotRegistered(AbstractPolymorphicSerializer.kt:114)
	at kotlinx.serialization.PolymorphicSerializerKt.findPolymorphicSerializer(PolymorphicSerializer.kt:109)
	at kotlinx.serialization.json.internal.StreamingJsonEncoder.encodeSerializableValue(StreamingJsonEncoder.kt:233)
	at kotlinx.serialization.json.internal.JsonStreamsKt.encodeByWriter(JsonStreams.kt:28)
	at kotlinx.serialization.json.Json.encodeToString(Json.kt:81)
But the docs suggest that a Set is serializable
a
LinkedHashSet
is custom class from Kotlin/JVM and it's not serializable like
Set
While Set is supported by Kotlin internally You can see in Kotlin source code:
Copy code
@SinceKotlin("1.1") public actual typealias LinkedHashSet<E> = java.util.LinkedHashSet<E>
While
Set
is fully supported by Kotlin which mean you can use it also in Kotlin/Native
o
@Ahmed Riyadh Thanks, LinkedHashSet is a Set so it is supported. The issue was that T was compiled to Any and Set<Any> leads to the error above so I have to write a serializer for it
In my case T is only one of the primitives though, is there any shortcut that can be taken?
a
> LinkedHashSet is a Set so it is supported. Make sure you are using the
LinkedHashSet
from
kotlin.collections
By manually use it, the IDE will use the one from
java.util.*
Example:
Copy code
private val rooms = Collections.synchronizedMap<String, Room>(kotlin.collections.LinkedHashMap())
I don't think that will solve the issue though since (since it's
typealias
)
o
The issue isnt that LinkedHashSet cant be serialized, it can, the issue is the generic type
This serializes
Whereas this does not
T becomes Any when compiled if the set contains a set of PatchOption<T> where T is multiple types