gsala
03/03/2021, 1:07 PM@Serializable
data class Folder(
val content: SingleOrCollection<File>
)
@Serializable
data class File(val name: String)
@Serializable
sealed class SingleOrCollection<T> {
@Serializable
@SerialName("single")
class Single<T>(val data: T) : SingleOrCollection<T>()
@Serializable
@SerialName("collection")
class Collection<T>(val data: List<T>) : SingleOrCollection<T>()
}
I get a an exception when trying to serialize Folder(SingleOrCollection.Single(File(fileName)))
with json.encodeToString(folder)
kotlinx.serialization.SerializationException: Class 'File' is not registered for polymorphic serialization in the scope of 'Any'.
Mark the base class as 'sealed' or register the serializer explicitly.
It seems looks like a pretty simple use case. Does anyone know what the issue could be?pdvrieze
03/03/2021, 2:39 PMCollection
and Single
are containers of polymorphic values. The base type is unconstrained (erasure) thus Any
. As such you need to create a serializersModule
that registers File
as a valid subtype for Any
.gsala
03/03/2021, 2:53 PMBothHow so? Can you explain this further?andCollection
are containers of polymorphic valuesSingle
pdvrieze
03/03/2021, 3:03 PMpdvrieze
03/03/2021, 3:05 PMgsala
03/03/2021, 8:37 PM