-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();
4
  • 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 minimal reproducible example would make it much easier to help you. Commented Feb 10, 2016 at 10:05
  • I want to change property name not it's value. Commented Feb 10, 2016 at 10:07
  • So please update your question with that information, along with a complete example showing what you've tried... Commented Feb 10, 2016 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. Commented Feb 10, 2016 at 10:15

1 Answer 1

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"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Jon got final solution. I am doing mistake like obj["name"] = "FirstName"; assignment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.