CSharp · Console
using System;
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.Name = "foo";
Console.WriteLine(JsonHelper.SerializeToMinimalJson(obj));
Console.WriteLine("--- test #3 ---");
obj = new ParentSample();
obj.Sample.Value = 3;
Console.WriteLine(JsonHelper.SerializeToMinimalJson(obj));
}
}
public class ParentSample
{
public Sample Sample { get; private set; }
public ParentSample()
{
Sample = new Sample();
}
}
public class Sample
{
public int Value { get; set; }
public string Name { get; set; }
}
public static class JsonHelper
{
public static string SerializeToMinimalJson(object obj)
{
return JToken.FromObject(obj).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) ||
(token.Type == JTokenType.String && token.ToString() == String.Empty) ||
(token.Type == JTokenType.Boolean && token.Value<bool>() == false) ||
(token.Type == JTokenType.Integer && token.Value<int>() == 0) ||
(token.Type == JTokenType.Float && token.Value<double>() == 0.0) ||
(token.Type == JTokenType.Null);
}
}