-2

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();
sushil
  • 301
  • 4
  • 16
  • It's not really clear what you mean by "I have key in json string". Nor is it clear whether you're trying to change the *name* of the property or the *value*. A [mcve] would make it much easier to help you. – Jon Skeet Feb 10 '16 at 10:05
  • I want to change property name not it's value. – sushil Feb 10 '16 at 10:07
  • So please update your question with that information, along with a complete example showing what you've tried... – Jon Skeet Feb 10 '16 at 10:08
  • @PieroAlberto: That question is about a situation where the code is using a serialized class. I don't see any indication of that here. – Jon Skeet Feb 10 '16 at 10:15

1 Answers1

3

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"
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks Jon got final solution. I am doing mistake like obj["name"] = "FirstName"; assignment. – sushil Feb 10 '16 at 10:25