JSON.NET 如何删除节点

JSON.NET how to remove nodes(JSON.NET 如何删除节点)

本文介绍了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.我想从 JSON 中去掉_metadata"和_some"节点.我正在使用 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 如何删除节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:JSON.NET 如何删除节点

基础教程推荐