kbson icon indicating copy to clipboard operation
kbson copied to clipboard

Look up the class discriminator value by its name in the PolymorphismDecoder

Open jenssuhr opened this issue 4 months ago • 0 comments

Current state

The PolymorphismDecoder expects the first field in the BSON document (or the second, if the first one is the _id) to contain the class discriminator. If the discriminator field is at another position in the document, deserialization fails.

Example: Parsing the following document

{
  "payload": {
    "_id": {
      "$oid": "5d1777814e8c7b408a6ada73"
    },
    "someData": "something",
    "___type": "com.github.jershell.kbson.models.polymorph.SMessage.DataWithObjectId"
  }
}

leads to

Serializer for subclass 'something' is not found in the polymorphic scope of 'SMessage'.
Check if class with serial name 'something' exists and serializer is registered in a corresponding SerializersModule.
To be registered automatically, class 'something' has to be '@Serializable', and the base class 'SMessage' has to be sealed and '@Serializable'.

Proposed solution

With this pull request, decodeElementIndex actively looks for a field with the configured class discriminator's name. It also allows removing the alreadyReadId parameters introduced in https://github.com/jershell/kbson/pull/19. This change adds a few more read calls, but I think the tradeoff is worth it for a bit more robustness.

jenssuhr avatar Sep 24 '24 08:09 jenssuhr