Skip to content

Support JsonObject Serialization/Deserialization in OData #1498

@Justinlcx

Description

@Justinlcx

We’re working on a use case where we need to handle JsonObject properties within our OData model. To achieve this, we’ve implemented custom serialization and deserialization logic, but we’ve encountered a few challenges that may indicate that we are not using the right path. We wishes to expose a JsonObject as an untyped Object.

Use Case

We want to expose a property of type JsonObject (We don't know the inside shape of the JSON, that is why we wish to have a JsonObject ) in our model and have it correctly serialized/deserialized as a JSON object in OData requests/responses.

Challenges & Workarounds

Model Definition
OData interprets JsonObject as IEnumerable<KeyValuePair<string, JsonNode>>, which causes it to treat the property as a list rather than a JSON object.
This would make the payload format different to what we expect.

Workaround:
We removed the all JsonObject from Entity and Complex type from the EDM Model, we builded the model and with the result we added back the removed properties but as untyped , which allows us to handle them as raw JSON ({}) in the payload.

Serialization

To bridge the EDM untyped object and the CLR JsonObject, we implemented a custom serializer:
1. Subclassed ODataResourceSerializer
2. Overrode CreateUntypedPropertyValue to return an ODataProperty with an ODataUntypedValue using the raw JSON string
3. This works as expected for serialization.

Deserialization

Deserialization is where we hit a blocker:

The CLR type (JsonObject) and EDM type (Untyped) mismatch causes the default deserialization to fail.
We implemented a custom ODataResourceDeserializer and overrode ApplyNestedProperty to handle this.
We use Delta and call delta.TrySetPropertyValue() to set the property.
However, during this process, we encounter an InvalidOperationException in CollectionDeserializationHelper.AddToCollectionCore, specifically when addMethod.Invoke() is called.

Is this a known limitation or bug in how OData handles untyped properties and JsonObject types? Or are we misusing the framework for this scenario?

We’ve created a repository Repo with a minimal reproduction of the issue for reference.

Any guidance or suggestions would be greatly appreciated!

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions