Can Newtonsoft Json.NET skip serializing empty lists?
Regarding David Jones' suggestion to use IContractResolver
, this works for me to cover all IEnumerables
variations without explicitly modifying the class that needs to be serialized:
public class ShouldSerializeContractResolver : DefaultContractResolver
{
public static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) {
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (property.PropertyType != typeof(string)) {
if (property.PropertyType.GetInterface(nameof(IEnumerable)) != null)
property.ShouldSerialize =
instance => (instance?.GetType().GetProperty(property.PropertyName).GetValue(instance) as IEnumerable<object>)?.Count() > 0;
}
return property;
}
}
Then I build it into my settings object:
static JsonSerializerSettings JsonSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = ShouldSerializeContractResolver.Instance,
};
and use it like this:
JsonConvert.SerializeObject(someObject, JsonSettings);
In case you didn't find a solution to this, the answer is remarkably simple when you manage to track it down.
If you are permitted to extend the original class then add a ShouldSerializePropertyName
function to it. This should return a Boolean indicating whether or not that property should be serialized for the current instance of the class. In your example this might look like this (not tested but you should get the picture):
public bool ShouldSerializeNumbers()
{
return _numbers.Count > 0;
}
This approach works for me (albeit in VB.NET). If you're not allowed to modify the original class then the IContractResolver
approach described on the the linked page is the way to go.