Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# remove json child node using newtonsoft

I am developing an app using c# wpf in .net 3.5. I use newtonsoft library to parse the json string.

I want to know how to remove a child node of json.

For example, My json data =

{"employees":[
{"firstName":"John", "lastName":"Doe"}, 
{"firstName":"Anna", "lastName":"Smith"}, 
{"firstName":"Peter", "lastName":"Jones"}]}

The function

jobject.Remove("employees");

removes all the nodes sucessfully

I would like to know how to remove the first employee detail alone.

like image 928
siva prasanna Avatar asked Feb 08 '15 06:02

siva prasanna


Video Answer


1 Answers

Once you parse your json into a JObject, the employees property will be a JArray. The JArray class has methods you're looking for, such as JArray.RemoveAt

The following code will do what you want

string json =
@"{
    ""employees"":[
        { ""firstName"":""John"", ""lastName"":""Doe""}, 
        { ""firstName"":""Anna"", ""lastName"":""Smith""}, 
        { ""firstName"":""Peter"", ""lastName"":""Jones""}
    ]
}";

dynamic obj = JObject.Parse(json);
(obj.employees as JArray).RemoveAt(0);

// obj now only has "Anna Smith" and "Peter Jones"

dynamic was introduced in .NET 4.0, so for 3.5 you'd use something like this instead

JObject obj = JObject.Parse(json);
(obj["employees"] as JArray).RemoveAt(0);
like image 106
gaiazov Avatar answered Oct 22 '22 23:10

gaiazov