Kotlinx.serialization: Add custom polymorphic serializers with embedded serialiModule

Created on 2 Nov 2019  路  4Comments  路  Source: Kotlin/kotlinx.serialization

What is your use-case and why do you need this feature?

Currently the only way to define polymorphic / sealed serialization is to provide a SerialModule for Encoder/Decoder during serialization. In many cases, one knows all necessary descendants at the moment of class creation, so it seems to be easier to create a custom serializer, than to define it at the use site. Also there is a case, where one needs different descendant list for the same parent in different places.

Describe the solution you'd like

It should be fairly simple to add custom polymorphic serializer with its own SerialModule defined inside the serializer itself. The internal module should override external module.

feature

Most helpful comment

When all subclasses and serializers are known in compile time, you can use SealedClassSerializer manually (after #572 is merged).

In the future, we have plans to allow users to implement AbstractPolymorphicSerializer where some more complicated strategies for findPolymorphicSerializer could be provided.

All 4 comments

Note that I've added a comment to the sealed classes pull request that basically relates to this: https://github.com/Kotlin/kotlinx.serialization/pull/572#issuecomment-542591357

When all subclasses and serializers are known in compile time, you can use SealedClassSerializer manually (after #572 is merged).

In the future, we have plans to allow users to implement AbstractPolymorphicSerializer where some more complicated strategies for findPolymorphicSerializer could be provided.

@sandwwraith Unfortunately it is not always possible to have the potential children be part of a sealed hierarchy. I might have a go at implementing the library part of this (an annotation and plugin based generation part would then be second - first support it in custom serializers).

I agree with @pdvrieze, but as far as I understood, one can use SealedClassSerializer with any set of descendants (even if they are not actually have sealed parent). If so, it should suffice for the most cases.

Was this page helpful?
0 / 5 - 0 ratings