How to change json property name dynamically in c#

How to Change JSON Property Name Dynamically in C#

To dynamically change a JSON property name in C#, you can use the Newtonsoft.Json library. This library provides powerful JSON manipulation capabilities.

Here is an example of how to change a JSON property name dynamically:


using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public static class JsonHelper
{
    public static string ChangeJsonPropertyName(string json, string oldPropertyName, string newPropertyName)
    {
        // Parse the JSON string into a JObject
        JObject obj = JObject.Parse(json);

        // Get the property to be renamed
        JProperty property = obj.Property(oldPropertyName);
        if (property != null)
        {
            // Remove the old property and add a new one with the new name
            property.Remove();
            obj.Add(new JProperty(newPropertyName, property.Value));
        }

        // Convert the modified JObject back to a JSON string
        return obj.ToString();
    }
}

// Example usage
string json = "{\"oldName\":\"Hello World!\"}";
string modifiedJson = JsonHelper.ChangeJsonPropertyName(json, "oldName", "newName");
Console.WriteLine(modifiedJson);
// Output: {"newName":"Hello World!"}
  

In the above example, we defined a helper class named JsonHelper that contains a method called ChangeJsonPropertyName. This method takes a JSON string, the old property name, and the new property name as parameters.

Inside the method, we first parse the JSON string into a JObject using the JObject.Parse method. Then, we retrieve the property with the old name using the obj.Property method. If the property exists, we remove it using the property.Remove method and add a new property with the new name using the obj.Add method.

Finally, we convert the modified JObject back to a JSON string using the obj.ToString method and return it.

In the example usage section, we demonstrate how to use the JsonHelper class to change the property name “oldName” to “newName” in a JSON string.

Leave a comment