JSON.NET如何删除节点
问题描述:
我有类似下面的JSON:
I have a json like the following:
{
"d": {
"results": [
{
"__metadata": {
},
"prop1": "value1",
"prop2": "value2",
"__some": "value"
},
{
"__metadata": {
},
"prop3": "value1",
"prop4": "value2",
"__some": "value"
},
]
}
}
我只想这个JSON转换为不同的JSON。我想去掉了_ 的元数据和的_some从JSON节点。我使用JSON.NET。
I just want to transform this JSON into a different JSON. I want to strip out the "_metadata" and "_some" nodes from the JSON. I'm using JSON.NET.
答
我刚刚结束了反序列化到JObject,并通过递归循环删除不需要的字段。下面是对于那些有兴趣的功能。
I just ended up deserializing to JObject and recursively looping through that to remove unwanted fields. Here's the function for those interested.
private void removeFields(JToken token, string[] fields)
{
JContainer container = token as JContainer;
if (container == null) return;
List<JToken> removeList = new List<JToken>();
foreach (JToken el in container.Children())
{
JProperty p = el as JProperty;
if (p != null && fields.Contains(p.Name))
{
removeList.Add(el);
}
removeFields(el, fields);
}
foreach (JToken el in removeList)
{
el.Remove();
}
}