Skip to content

Commit

Permalink
Make IgnoreEmptyCollectionsContractResolver special case ICollection.…
Browse files Browse the repository at this point in the history
…Count check (#1759)
  • Loading branch information
lahma authored Nov 25, 2024
1 parent 4588ef2 commit c740804
Showing 1 changed file with 12 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,30 @@ namespace NJsonSchema.Infrastructure
{
internal sealed class IgnoreEmptyCollectionsContractResolver : PropertyRenameAndIgnoreSerializerContractResolver
{
private static readonly TypeInfo enumerableType = typeof(IEnumerable).GetTypeInfo();

protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);

if ((property.Required == Required.Default || property.Required == Required.DisallowNull) &&
if (property.Required is Required.Default or Required.DisallowNull &&
property.PropertyType is { IsPrimitive: false } &&
property.PropertyType != typeof(string) &&
typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(property.PropertyType?.GetTypeInfo()))
enumerableType.IsAssignableFrom(property.PropertyType.GetTypeInfo()))
{
property.ShouldSerialize = instance =>
{
var enumerable = instance != null ? property.ValueProvider?.GetValue(instance) as IEnumerable : null;
if (enumerable != null)
var value = instance != null ? property.ValueProvider?.GetValue(instance) : null;
if (value is ICollection collection)
{
return enumerable.GetEnumerator().MoveNext();
return collection.Count > 0;
}
else
if (value is IEnumerable enumerable)
{
return true;
return enumerable.GetEnumerator().MoveNext();
}
return true;
};
}

Expand Down

0 comments on commit c740804

Please sign in to comment.