0

I have the need to do an implementation with along the lines of custom type handling in .NET.

Scenario is, we have a Redis datastore that stores our models serialized in to JSON using Newtonsoft. We anticipate that we will be using the same store from multiple services in the future to fetch data. Due to this, we don't want to use inbuilt type handling since then the other services which uses Newtonsoft to deserialize will break due to them not having objects with the same namespace.

My idea is to manually push a new property like "__type" with the type and "__namespace" with the namespace. Basically I want to not have the "$type" metadata key name and instead have another key to it. I have already implemented a JsonConverter but it's like reinventing the wheel and performance wise, it may not be the best.

Is there a straightforward way of doing this other than implementing the whole serialization and deserialization logic? Can we interpret the lifecycle and do a little manipulation?

Note that this needs to be a generic solution. It should work for all types.

Sahan
  • 1
  • You cannot change Json.NET's [`$type`](https://www.newtonsoft.com/json/help/html/serializetypenamehandling.htm) to another name, it's hardcoded. See [JSON.Net - Change $type field to another name?](https://stackoverflow.com/q/9490345). You can control its value via a serialization binder, see [Custom $type value for serialized objects](https://stackoverflow.com/q/49283251). – dbc May 22 '23 at 12:46
  • 1
    As an aside, with System.Text.Json you can change the name of the type property to `"__type"` by setting [`JsonPolymorphicAttribute.TypeDiscriminatorPropertyName`](https://docs.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonpolymorphicattribute.typediscriminatorpropertyname), see [this answer](https://stackoverflow.com/a/74352597) to [Is polymorphic deserialization possible in System.Text.Json?](https://stackoverflow.com/q/58074304). But there is no way to use two separate properties to encode the type name and namespace. – dbc May 22 '23 at 12:50

0 Answers0