JSON.NET如何删除节点 [英] JSON.NET how to remove nodes

查看:821
本文介绍了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();
    }
}

这篇关于JSON.NET如何删除节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆