Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make IgnoreEmptyCollectionsContractResolver special case ICollection.Count check #1759

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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