Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support customization of polymorphic discriminator field for individual types #1410

Closed
diesieben07 opened this issue Apr 9, 2021 · 2 comments
Labels

Comments

@diesieben07
Copy link

diesieben07 commented Apr 9, 2021

What is your use-case and why do you need this feature?
I am using kotlinx.serialization to consume a JSON document from a third party (in particular I am parsing an OpenAPI Document). As such I cannot change the format of the JSON.
At various places in the specification, a polymorphic discriminator is used (such as in for parameters or type for security schemes). Even though the polymorphic serializer is perfectly capable of deserializing these types on their own, it is impossible to deserialize a document containing them both, because the discriminator property name is configured globally.
As such a completely custom deserializer must be used. PolymorphicSerializer cannot be subclassed and even subclassing the internal AbstractPolymorphicSerializer will not work because StreamingJsonDecoder will just ignore you and completely bypass the AbstractPolymorphicSerializer (see Polymorphic.kt).

To be honest, I find it perplexing that it is possible to override the discriminator property name on a global level at all - the Json serializer has no business in deciding what this property should be called, it depends on the actual type being serialized.

Describe the solution you'd like
I would like an annotation similar to @SerialName which can be used on a class to set the discriminator property name used for its children.

@Serializable
@PolymorphicDiscriminator("discriminator")
sealed class BaseClass

@SerialName("foo")
@Serializable
class Foo : BaseClass()

@SerialName("bar")
@Serializable
class Bar : BaseClass()

Should produce JSON as follows:

{
  "discriminator": "foo"
}
@Dominaezzz
Copy link
Contributor

#546

@diesieben07
Copy link
Author

Thank you, I did search but didn't find that one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants