IgnoreEmptyCollectionsContractResolver
sealed class IgnoreEmptyCollectionsContractResolver : PropertyRenameAndIgnoreSerializerContractResolver
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace NJsonSchema.Infrastructure
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
internal sealed class IgnoreEmptyCollectionsContractResolver : PropertyRenameAndIgnoreSerializerContractResolver
{
private static readonly Type enumerableType = typeof(IEnumerable);
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
Required required = property.Required;
if ((required == Required.Default || required == Required.DisallowNull) ? true : false) {
Type propertyType = property.PropertyType;
if ((object)propertyType != null && !propertyType.IsPrimitive && property.PropertyType != typeof(string) && enumerableType.IsAssignableFrom(property.PropertyType))
property.ShouldSerialize = delegate(object instance) {
object obj = (instance == null) ? null : property.ValueProvider?.GetValue(instance);
ICollection collection = obj as ICollection;
if (collection != null)
return collection.Count > 0;
return (obj as IEnumerable)?.GetEnumerator().MoveNext() ?? true;
};
}
return property;
}
}
}