avro-kotlin / avro4k

Avro format support for Kotlin
Apache License 2.0
197 stars 37 forks source link

SerializationException when using MapSerializer as root serializer #116

Closed FranziskusW closed 9 months ago

FranziskusW commented 3 years ago

I am using Avro.default.toRecord(serializer, data) with a MapSerializer(String.serializer(), String.serializer(). As it returns kotlinx.serialization.SerializationException: Unsupported root element passed to root record encoder I investigated and found the following snippet in

override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder {
      return when (descriptor.kind) {
         is StructureKind.CLASS -> RecordEncoder(schema, serializersModule, callback)
         is PolymorphicKind -> UnionEncoder(schema,serializersModule,callback)
         else -> throw SerializationException("Unsupported root element passed to root record encoder")
      }
}

It seems that StructureKind.CLASS is the culprit. It contains an object of that type, but the kotlin is-comparator expects a type.

FranziskusW commented 3 years ago

As a minimal example for reproduction, you can try this:

import kotlinx.serialization.SerializationException
 import kotlinx.serialization.builtins.MapSerializer
 import kotlinx.serialization.descriptors.PolymorphicKind
 import kotlinx.serialization.descriptors.StructureKind

 import kotlinx.serialization.builtins.serializer
 println(
     when (MapSerializer(String.serializer(), String.serializer()).descriptor.kind) {
         is StructureKind -> "StructureKind.CLASS"
         is PolymorphicKind -> "PolymorphicKind"
         else -> throw SerializationException("Unsupported root element passed to root record encoder")
     }
 )
FranziskusW commented 3 years ago

Is this a restriction of AVro itself? Not allowing a Map as root element?

thake commented 3 years ago

Currently avro4k only supports data classes as roots. But it should be possible to also support all other types. Do you want to give it a try and provide a pr?

Chuckame commented 1 year ago

Closing stale issue. By the way, we are planning to handle non-record values

Chuckame commented 9 months ago

Closing this issue, as it will be covered by #187 and #114