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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With