【问题标题】:How to recursively delete empty keys in json in c# using Newtonsoft?如何使用 Newtonsoft 在 c# 中递归删除 json 中的空键?
【发布时间】:2015-10-22 23:55:04
【问题描述】:

{"a":1,"b":{"c":{}},"d":{"e":1,"f":{"g":{}}}}

这是一个简单的json,如何从json中递归删除空键 所以输出应该在这里

{"a":1,"d":{"e":1}}

我试过的东西 removeEmptyDocs(token,"{}")

   private void removeEmptyDocs(JToken token, string empty)
        {
            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 && empty.Contains(p.Value.ToString()))
                {
                    removeList.Add(el);
                }

                removeEmptyDocs(el, empty);
            }

            foreach (JToken el in removeList)
            {

                el.Remove();

            }
        }

【问题讨论】:

    标签: c# json recursion json.net


    【解决方案1】:

    您不能在迭代时移除标记,因此您应该在收集完所有空叶子后执行此操作。这是代码,它不是最佳的,而是一个很好的起点。它做了预期的事情

    class Program
    {
        static void Main(string[] args)
        {
            var json =
               "{'a': 1, 'b': {'c': {}, k: [], z: [1, 3]},'d': {'e': 1,'f': {'g': {}}}}";
            var parsed = (JContainer)JsonConvert.DeserializeObject(json);
            var nodesToDelete = new List<JToken>();
    
            do
            {
                nodesToDelete.Clear();
    
                ClearEmpty(parsed, nodesToDelete);
    
                foreach (var token in nodesToDelete)
                {
                    token.Remove();
                }
            } while (nodesToDelete.Count > 0);
    
        }
    
        private static void ClearEmpty(JContainer container, List<JToken> nodesToDelete)
        {
            if (container == null) return;
    
            foreach (var child in container.Children())
            {
                var cont = child as JContainer;
    
                if (child.Type == JTokenType.Property ||
                    child.Type == JTokenType.Object ||
                    child.Type == JTokenType.Array)
                {
                    if (child.HasValues)
                    {
                        ClearEmpty(cont, nodesToDelete);
                    }
                    else
                    {
                        nodesToDelete.Add(child.Parent);
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-02
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      • 2017-12-08
      • 2013-04-25
      • 2021-04-25
      • 1970-01-01
      • 2014-06-22
      相关资源
      最近更新 更多