Search code examples
c#json.netnamespacesprefix

Prepend namespace to dynamic JSON objects keys using C#


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


Solution

  • 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