using System.ComponentModel;
using Newtonsoft.Json.Linq;
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.Name = "blah";
Console.WriteLine(JsonHelper.SerializeToMinimalJson(obj));
Console.WriteLine("--- test #3 ---");
obj = new ParentSample();
Console.WriteLine(JsonHelper.SerializeToMinimalJson(obj));
public class ParentSample
public Sample Sample { get; private set; }
public int Value { get; set; }
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;
child = child.RemoveEmptyChildren();
if (!child.IsEmptyOrDefault())
copy.Add(prop.Name, child);
else if (token.Type == JTokenType.Array)
JArray copy = new JArray();
foreach (JToken item in token.Children())
child = child.RemoveEmptyChildren();
if (!child.IsEmptyOrDefault())
public static bool IsEmptyOrDefault(this JToken token)
return (token.Type == JTokenType.Array && !token.HasValues) ||
(token.Type == JTokenType.Object && !token.HasValues);