I think I'm missing something on polymorphic deser...
# serialization
z
I think I'm missing something on polymorphic deserialization. I have an archive-like file format, with elements like Files and Folders. A Folder can contain Files, or other Folders, or a mix of both. All entries have a header. The type of entry is encoded within that header. If the first 4 bytes of of the header are
GRUP
, it is a Folder. If it is anything else, it is a File. During serialization, it tries to encode the full name of the type. I don't seem to be able to customize the discriminator behavior, and during deserialization, I get errors like > kotlinx.serialization.SerializationException: Invalid index in polymorphic deserialization of unknown class > Expected 0, 1 or DECODE_DONE(-1), but found -3 Ultimately, I'm wondering how to model this. My current method has been a
List<FolderChild>
, but I don't think there's enough type information to do what I'm trying to do.
Actually, that error seems to only be related to my implementation of decodeElementIndex. For that question, what is the correct way to implement element index for a list of polymorphic values?
List of 1 element, being a polymorphic class of 2 elements?
b
Do you have your own `Format`/`Encoder`/`Decoder`? Because one option might be having a
decodeEntryType()
or
decodeEntryHeader()
function in your
Decoder
, that way your polymorphic serializer can peek at the the type to know what deserializer to use, and delegate to the appropriate deserializer. I'm doing something similar in a format I maintain, and I'm basing it off kxs's
Decoder.decodeNotNullMark()
, which similarly let's you peek at type information. Either that, or similar to what the Json format does, you can add a
decodeEntry()
function to your Decoder and have your serializer lean into that. Similar to how
JsonElementSerializer
just calls
decodeJsonElement()
. Polymorphism in general still seems like it's being designed (since PolymorphicKind is experimental), so I'm not sure there's a recommended approach yet or how things might change later on.