[Fork] StackOverflow Q33027409

CSharp · Console

/Program.cs

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
					
public class Program
{
	public static void Main()
	{
		string json = @"
		{
			""Foo"": {
				""P1"": null,
				""P2"": ""hello world"",
				""P3"": null,
				""P4"": {
					""P1"": 1,
					""P2"": null,
					""P3"": null
				},
				""FooArray"": [
					{
						""F1"": null,
						""F2"": null,
						""F3"": null
					}
				]
			},
			""Bar"": null
		}";
		
		JToken token = JsonHelper.RemoveEmptyChildren(JToken.Parse(json));
		Console.WriteLine(token.ToString(Formatting.Indented));
	}
}


public static class JsonHelper
{
    public static JToken RemoveEmptyChildren(JToken token)
    {
        if (token.Type == JTokenType.Object)
        {
            JObject copy = new JObject();
            foreach (JProperty prop in token.Children<JProperty>())
            {
                JToken child = prop.Value;
                if (child.HasValues)
                {
                    child = RemoveEmptyChildren(child);
                }
                if (!IsEmpty(child))
                {
                    copy.Add(prop.Name, child);
                }
            }
            return copy;
        }
        else if (token.Type == JTokenType.Array)
        {
            JArray copy = new JArray();
            foreach (JToken item in token.Children())
            {
                JToken child = item;
                if (child.HasValues)
                {
                    child = RemoveEmptyChildren(child);
                }
                if (!IsEmpty(child))
                {
                    copy.Add(child);
                }
            }
            return copy;
        }
        return token;
    }

    public static bool IsEmpty(JToken token)
    {
        return (token.Type == JTokenType.Null);
    }
}
;