Skip to content

Polymorphic type determined by side property value #471

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

Closed
jimirocks opened this issue May 28, 2019 · 0 comments
Closed

Polymorphic type determined by side property value #471

jimirocks opened this issue May 28, 2019 · 0 comments
Labels

Comments

@jimirocks
Copy link

Some API returns json like this:

{ "control": "type1/X", "value": { "a": "a"}}
{ "control": "type1/Y", "value": { "a": "b"}}
{ "control": "type2/X", "value": { "c": "d"}}

Ideally I would write sealed class Value, but is there a way to let kotlinx.serialization pick up the correct serializer for value based on the property control. Moreover the control property is not an object type discriminator, but different prefixes maps to different values. In Jackson once can use TypeIdResolver for this.

I tried to write some custom serializer - while serialization is just fine, the deserialization is problematic - since there is no guarantee the control property comes sooner than value so the code below doesn't work:

loop@ while (true) {
                when (val i = compositeDecoder.decodeElementIndex(descriptor)) {
                    CompositeDecoder.READ_DONE -> break@loop
                    0 -> control = compositeDecoder.decodeStringElement(descriptor, i)
                    1 -> value = compositeDecoder.decodeSerializableElement(descriptor, i, chooseSerializer(control))
                    else -> throw SerializationException("Unknown index $i")
                }
            }

Additionaly I didn't find a way how to "remember raw value" for later decoding based on control

Thanks for help

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