0

I have a business case where I need to take any incoming JSON payload (so the JSON object will have to be dynamic, not predefined by a C# class) and prepend a given namespace to all its containing keys.

For example if the following payload comes in:

{
  "property1": "value1",
  "property2": 2,
  "property3": true,
  "property4": {
    "myArray": [
      {
        "arrayProperty1": "im the first object in array",
        "arrayProperty2": "some value"
      },
      {
        "arrayProperty1": "im the second object in array",
        "arrayProperty2": "some value"
      }
    ]
  }
}

Then it needs to result in the following output:

{
  "mynamespace.property1": "value1",
  "mynamespace.property2": 2,
  "mynamespace.property3": true,
  "mynamespace.subObj": {
    "mynamespace.myArray": [
      {
        "mynamespace.arrayProperty1": "im the first object in array",
        "mynamespace.arrayProperty2": "some value"
      },
      {
        "mynamespace.arrayProperty1": "im the second object in array",
        "mynamespace.arrayProperty2": "some value"
      }
    ]
  }
}

Is this possible using C#? I tried searching for any similar question here on stackoverflow but this is the closest I got (they're using javascript): Prepending namespace to all of a JSON object's Keys

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
onmi
  • 87
  • 1
  • 9
  • If you use [tag:json.net] you could use `PropertyNameMappingJsonReader` from [this answer](https://stackoverflow.com/a/47539562/3744182) to [Change key name of data loaded through JsonExtensionData](https://stackoverflow.com/q/47529655/3744182) to add the namespace prefix. Then use that reader to deserialize to `JToken`, or stream directly to an output `StringWriter` as shown in [this answer](https://stackoverflow.com/a/30329731/3744182) to [How do I get formatted JSON in .NET using C#?](https://stackoverflow.com/q/2661063/3744182). – dbc Mar 30 '21 at 18:07

1 Answers1

1

You can make a short helper method using Json.Net's LINQ-to-JSON API (JTokens) to accomplish this:

public static string AddPrefixToAllKeys(string json, string prefix)
{
    JContainer token = (JContainer)JToken.Parse(json);

    // Note: We need to process the descendants in reverse order here
    // to ensure we replace child properties before their respective parents
    foreach (JProperty prop in token.Descendants().OfType<JProperty>().Reverse().ToList())
    {
        prop.Replace(new JProperty(prefix + prop.Name, prop.Value));
    }
    
    return token.ToString();
}

Then use it like this:

string modifiedJson = AddPrefixToAllKeys(originalJson, "mynamespace.");

Working demo here: https://dotnetfiddle.net/AdkAO7

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300