https://stackoverflow.com/questions/66875976

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
					
public class Program
{
	public static void Main()
	{
        string json = @"
            {
              ""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""
                  }
                ]
              }
            }";		

		string json1 = AddPrefixToAllKeys(json, "mynamespace.");
		Console.WriteLine(json1);

	}
	
	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();
	}
}
;