使用newtonsoft C#删除json的子节点 [英] C# remove json child node using newtonsoft
问题描述
我正在开发使用.NET 3.5的WPF C#应用程序。
我用newtonsoft库解析JSON字符串。
I am developing an app using c# wpf in .net 3.5. I use newtonsoft library to parse the json string.
我想知道如何删除JSON的子节点。
I want to know how to remove a child node of json.
例如,
我的JSON数据=
For example, My json data =
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}]}
功能
jobject.Remove("employees");
成功地删除所有的节点
我想知道如何只除去第一个雇员的细节。
I would like to know how to remove the first employee detail alone.
推荐答案
一旦你解析你的JSON成 JObject
,员工财产将是一个 JArray
。在 JArray
类有你要找的方法,如 JArray.RemoveAt
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"
动态
介绍在.NET 4.0中,因此对于3.5,你会使用这样的事情,而不是
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);
这篇关于使用newtonsoft C#删除json的子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!