0

I have the below sample JSON:

[
  {
    "$type": "TestProject.Classes.TestClass, TestProject",
    "Name": "TestCommand",
    "Children": [
      {
        "Age": 0,
        "Eta": 8,
        "Gender": "Ragel"
      },
      {
        "Age": 0,
        "Eta": 20,
        "Gender": "Mara"
      }
    ],
    "School": {
      "Title": "School for Life"
    }
  }
]

This is deserialized from a data source (message in the message queue). There are some types which have changed in the codebase, and I would like to still be able to map the old types to the new ones.

For the example, let's imagine the type TestClass no longer exists, but now is TestClassNew. I have mappings stored to be able to map from the old to the new type. I am trying to alter the $type value prior to the object being deserialised, such that its string value is changed from TestProject.Classes.TestClass, TestProject to TestProject.Classes.TestClassNew, TestProject.

I was trying using a JsonConvertor, but not sure if that is the right way - haven't managed to do it. Any help on how this can be done would be appreciated.

Karl Cassar
  • 6,043
  • 10
  • 47
  • 84
  • If you are using a version of Json.NET before 10.0, take a look at [How to create a SerializationBinder for the Binary Formatter that handles the moving of types from one assembly and namespace to another](https://stackoverflow.com/q/19666511). If you are using a later version then Json.NET now uses [`ISerializationBinder`](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Serialization_ISerializationBinder.htm) but the idea is the same, see [Custom SerializationBinder](https://www.newtonsoft.com/json/help/html/SerializeSerializationBinder.htm). – dbc May 29 '18 at 17:21
  • It's a good idea to have a custom serialization binder that sanitizes incoming types anyway for security reasons, see [TypeNameHandling caution in Newtonsoft Json](https://stackoverflow.com/a/39614563). – dbc May 29 '18 at 17:22
  • Or wait - do you not know the new `"$type"` based on the old `"$type"` and need to look at the actual properties present? Your question title says *based on property name and value* but your question text doesn't really reflect this. – dbc May 29 '18 at 17:25

0 Answers0