CSharp · Console
using System;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class Program
{
public static void Main()
{
Foo foo = new Foo
{
Something = "This is something",
Nothing = null,
Number = 5,
Child = new Foo
{
Something = "Child Object",
Nothing = null,
Number = 6,
Child = null
}
};
JsonSerializerSettings settings = new JsonSerializerSettings
{
ContractResolver = new NullSubstitutionPropertyValueResolver("Nothing to see here"),
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(foo, settings);
Console.WriteLine(json);
}
}
public class Foo
{
public string Something { get; set; }
public string Nothing { get; set; }
public int Number { get; set; }
public Foo Child { get; set; }
}
public class NullSubstitutionPropertyValueResolver : DefaultContractResolver
{
private readonly string _substitutionValue;
public NullSubstitutionPropertyValueResolver(string substitutionValue)
{
_substitutionValue = substitutionValue;
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty result = base.CreateProperty(member, memberSerialization);
PropertyInfo property = member as PropertyInfo;
if (property.PropertyType == typeof(string))
{
result.ValueProvider = new StringValueProvider(property, _substitutionValue);
}
return result;
}
}
public class StringValueProvider : IValueProvider
{
private PropertyInfo _targetProperty;
private string _substitutionValue;
public StringValueProvider(PropertyInfo targetProperty, string substitutionValue)
{
_targetProperty = targetProperty;
_substitutionValue = substitutionValue;
}
// SetValue gets called by Json.Net during deserialization.
// The value parameter has the original value read from the JSON;
// target is the object on which to set the value.
public void SetValue(object target, object value)
{
_targetProperty.SetValue(target, value);
}
// GetValue is called by Json.Net during serialization.
// The target parameter has the object from which to read the value;
// the return value is what gets written to the JSON
public object GetValue(object target)
{
object value = _targetProperty.GetValue(target);
return value == null ? _substitutionValue : value;
}
}