Search code examples
c#json.net

How to change property/Attribute from JSON string in c#?


I am having JSON string like

{"name":"studentname","Lastname":"lastnameofstudent"}

I want to change the name property/key to FirstName not the value of this property. using Newtonsoft JSON lib.

Example:

string json = @"{
  'name': 'SUSHIL'
}";
JObject obj = JObject.Parse(json);
var abc = obj["name"];
obj["name"] = "FirstName";
string result = obj.ToString();

Solution

  • The simplest way is probably just to assign a new property value, then call Remove for the old one:

    using System;
    using Newtonsoft.Json.Linq;
    
    class Test
    {
        static void Main()
        {
            string json = "{ 'name': 'SUSHIL' }";
            JObject obj = JObject.Parse(json);
            obj["FirstName"] = obj["name"];
            obj.Remove("name");
            Console.WriteLine(obj);
        }
    }
    

    Output:

    {
      "FirstName": "SUSHIL"
    }