https://stackoverflow.com/questions/58323355

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 = @"
            {
              ""A"": {
                ""B"": {
                  ""C"": ""12""
                }
              }
            }";
		
		var nameMappings = new Dictionary<string, string>
		{
			{ "A", "A1" },
			{ "B", "B1" },
			{ "C", "C1" }
		};

		string json1 = RenameProperties(json, nameMappings);
		Console.WriteLine(json1);

	}
	
	public static string RenameProperties(string json, Dictionary<string, string> nameMappings)
	{
		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())
		{
			if (nameMappings.TryGetValue(prop.Name, out string newName))
			{
				prop.Replace(new JProperty(newName, prop.Value));
			}
		}
		
		return token.ToString();
	}
}
;