[Fork] http://stackoverflow.com/questions/36884902/how-to-omit-ignore-skip-empty-object-literals-in-the-produced-json

CSharp · Console

/Program.cs

using System;
using System.ComponentModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
					
public class Program
{
	public static void Main()
	{
		Console.WriteLine("--- test #1 ---");
		var obj = new ParentSample();
		Console.WriteLine(JsonHelper.SerializeToMinimalJson(obj));
		
		Console.WriteLine("--- test #2 ---");
		obj = new ParentSample();
		obj.Sample.Value = 1;
		obj.Sample.Name = "blah";
		Console.WriteLine(JsonHelper.SerializeToMinimalJson(obj));
		
		Console.WriteLine("--- test #3 ---");
		obj = new ParentSample();
		obj.Sample.Value = 3;
		obj.Sample.Name = "foo";
		Console.WriteLine(JsonHelper.SerializeToMinimalJson(obj));
		
	}
}

public class ParentSample 
{
	public Sample Sample { get; private set; }
	public ParentSample() 
	{
		Sample = new Sample();
	}
}

public class Sample 
{
	[DefaultValue(3)]
	public int Value { get; set; }
	[DefaultValue("foo")]
	public string Name { get; set; }
}



public static class JsonHelper
{
	public static string SerializeToMinimalJson(object obj)
	{
		var serializer = new JsonSerializer();
		serializer.NullValueHandling = NullValueHandling.Ignore;
		serializer.DefaultValueHandling = DefaultValueHandling.Ignore;
		return JToken.FromObject(obj, serializer).RemoveEmptyChildren().ToString();
	}
	
    public static JToken RemoveEmptyChildren(this 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 = child.RemoveEmptyChildren();
                }
                if (!child.IsEmptyOrDefault())
                {
                    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 = child.RemoveEmptyChildren();
                }
                if (!child.IsEmptyOrDefault())
                {
                    copy.Add(child);
                }
            }
            return copy;
        }
        return token;
    }

    public static bool IsEmptyOrDefault(this JToken token)
    {
        return (token.Type == JTokenType.Array && !token.HasValues) ||
               (token.Type == JTokenType.Object && !token.HasValues);
    }

}
;