JSON.NET serialize JObject while ignoring null properties

后端 未结 4 1891
说谎
说谎 2020-12-01 16:37

I have a JObject which is used as a template for calling RESTful web services. This JObject gets created via a parser and since it

4条回答
  •  生来不讨喜
    2020-12-01 16:59

    Brian's answer works. I also came up with another (yet still recursive) way of doing it shortly after posting the question, in case anyone else is interested.

    private void RemoveNullNodes(JToken root)
    {
        if (root is JValue)
        {
            if (((JValue)root).Value == null)
            {
                ((JValue)root).Parent.Remove();
            }
        }
        else if (root is JArray)
        {
            ((JArray)root).ToList().ForEach(n => RemoveNullNodes(n));
            if (!(((JArray)root)).HasValues)
            {
                root.Parent.Remove();
            }
        }
        else if (root is JProperty)
        {
            RemoveNullNodes(((JProperty)root).Value);
        }
        else
        {
            var children = ((JObject)root).Properties().ToList();
            children.ForEach(n => RemoveNullNodes(n));
    
            if (!((JObject)root).HasValues)
            {
                if (((JObject)root).Parent is JArray)
                {
                    ((JArray)root.Parent).Where(x => !x.HasValues).ToList().ForEach(n => n.Remove());
                }
                else
                {
                    var propertyParent = ((JObject)root).Parent;
                    while (!(propertyParent is JProperty))
                    {
                        propertyParent = propertyParent.Parent;
                    }
                    propertyParent.Remove();
                }
            }
        }
    }
    

提交回复
热议问题