如何使用Newtonsoft在c#中以递归方式删除json中的空键?

时间:2015-07-31 10:23:32

标签: c# json recursion json.net

{"":1," B" {" C":{}}," d" {&# 34; E":1," F" {" G":{}}}}

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

{"":1," d" {" E":1}}

我试过的东西 removeEmptyDocs(令牌," {}&#34)

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

            }
        }

1 个答案:

答案 0 :(得分: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);
                }
            }
        }
    }
}