JSON.NET how to remove nodes(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 如何删除节点
				
        
 
            
        - CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
 - C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
 - 使用 rss + c# 2022-01-01
 - 带问号的 nvarchar 列结果 2022-01-01
 - 在 LINQ to SQL 中使用 contains() 2022-01-01
 - Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
 - Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
 - 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
 - 在 C# 中异步处理项目队列 2022-01-01
 - 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
 
						
						
						
						
						