Home > database >  How to dynamically handle changes in a JSON object name that may change regularly, when building C#
How to dynamically handle changes in a JSON object name that may change regularly, when building C#

Time:11-17

my predicament is that I have to deserialize some JSON files provided by my company's software eng department, for me to use in a production environment, however some revisions of the JSON files have objects or keys where the name had been modified (E.g. "EngineTemp":400 to "EngTemp":400).

I can easily deserialize everything in C# when the names don't change, but I find myself having to modify my class property names or class names themselves, to match the JSON revisions (because I know they need to be the same). However, manually reading through each JSON file when it gets revised to check for name changes is very time-consuming, and some of these files have hundreds of objects.

Currently I have no way to ensure the software eng team keeps the same names from revision to revision, so I really hope there is a way to handle this in a less manual fashion.

I can't provide any snippets of the JSON unfortunately because it's proprietary information, but the above example is basically what I want to account for.

I appreciate all suggestions!

As mentioned previously, I haven't come up with any good way of handling this in code yet, since it deals with changing the actual class and property names in my C#, to match the revisions in the JSON if they are altered.

CodePudding user response:

Ok, there's no really good solutions to this, but if there's a limited number of names, they use, then you can use a regex on the raw json data and replace with the name of your property. Then when you deserialize, the replaced name will work.

The regex can be rather simple:

(?<=")(EngineTemp|EngTemp|OtherName)(?=":)

It simply selects one of the known names surrounded by quotes and ending with colon :.

Use it like this:

string json = File.ReadAllText("path");

Regex jsonRegex = new Regex(@"(?<="")(EngineTemp|EngTemp|OtherName)(?="":)";

if (!jsonRegex.IsMatch(json)
{
    MessageBox.Show("ERROR", "Could not find the name\nYou must scan the json manually");
}

string fixedJson = jsonRegex.Replace(json, "YourProperty");

Now you can deserialize the json without recompiling as long as the used name is in the regex.

The code shows a messagebox, if they have changed to an unknown name. Then find the new name add it to the list in regex.

CodePudding user response:

You can deserialize to a dynamic object using System.Text.Json (assuming .NET core), otherwise you can find suitable deserialization libraries that can do the same.

dynamic result = JsonConvert.DeserializeObject<dynamic>(inputString)!;

Then access your properties via duck typing

result.EngTemp 

or via indexer

result["EngTemp"]
  • Related