Skip to content

Instantly share code, notes, and snippets.

@juanonsoftware
Last active August 29, 2015 14:23
Show Gist options
  • Save juanonsoftware/7067ce53813201abbdae to your computer and use it in GitHub Desktop.
Save juanonsoftware/7067ce53813201abbdae to your computer and use it in GitHub Desktop.
C# Convert null property to Empty JSON object by property's type
namespace JsonConvertNullToEmpty
{
public class Main
{
public Child First
{
get;
set;
}
public Child Last
{
get;
set;
}
}
public class Child
{
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var m = new Main()
{
First = new Child()
{
Name = "C1",
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new NullToEmptyObjectResolver(typeof(Child))
};
var str = JsonConvert.SerializeObject(m, settings);
}
}
class NullToEmptyObjectResolver : DefaultContractResolver
{
private readonly Type[] _types;
public NullToEmptyObjectResolver(params Type[] types)
{
_types = types;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
return type.GetProperties().Select(p =>
{
var jp = base.CreateProperty(p, memberSerialization);
jp.ValueProvider = new NullToEmptyValueProvider(p, _types);
return jp;
}).ToList();
}
}
class NullToEmptyValueProvider : IValueProvider
{
readonly PropertyInfo _memberInfo;
private readonly Type[] _types;
public NullToEmptyValueProvider(PropertyInfo memberInfo, params Type[] types)
{
_memberInfo = memberInfo;
_types = types;
}
public object GetValue(object target)
{
var result = _memberInfo.GetValue(target);
if (_types.Contains(_memberInfo.PropertyType) && result == null)
{
result = new object();
}
return result;
}
public void SetValue(object target, object value)
{
_memberInfo.SetValue(target, value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment