From 0444f8630aa4d29f2ec090a9dd702400b7b0e7dc Mon Sep 17 00:00:00 2001 From: half-ogre Date: Mon, 7 Oct 2013 17:06:20 -0700 Subject: [PATCH] omit null values from serialized objects --- Octokit/Http/SimpleJsonSerializer.cs | 34 +++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/Octokit/Http/SimpleJsonSerializer.cs b/Octokit/Http/SimpleJsonSerializer.cs index 8c846cf4..8876b95b 100644 --- a/Octokit/Http/SimpleJsonSerializer.cs +++ b/Octokit/Http/SimpleJsonSerializer.cs @@ -1,4 +1,10 @@ -namespace Octokit.Http +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using Octokit.Reflection; + +namespace Octokit.Http { public class SimpleJsonSerializer : IJsonSerializer { @@ -20,6 +26,32 @@ { return clrPropertyName.ToRubyCase(); } + + // This is overridden so that null values are omitted from serialized objects. + [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification = "Need to support .NET 2")] + protected override bool TrySerializeUnknownTypes(object input, out object output) + { + if (input == null) throw new ArgumentNullException("input"); + output = null; + Type type = input.GetType(); + if (type.FullName == null) + return false; + IDictionary obj = new JsonObject(); + IDictionary getters = GetCache[type]; + foreach (KeyValuePair getter in getters) + { + if (getter.Value != null) + { + var value = getter.Value(input); + if (value == null) + continue; + + obj.Add(MapClrMemberNameToJsonFieldName(getter.Key), value); + } + } + output = obj; + return true; + } } } }