如何使用Newtonsoft递归删除c#中json中的空键

本文关键字:json 何使用 Newtonsoft 递归 删除 | 更新日期: 2023-09-27 18:05:47

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

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

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

我试过的东西removeEmptyDocs(令牌,"{}"(

   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();
            }
        }

如何使用Newtonsoft递归删除c#中json中的空键

迭代时不能删除标记,所以应该在收集完所有空叶子后再删除。这是代码,它不是最优的,但它是一个很好的起点。它做了预期的

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);
                }
            }
        }
    }
}