From c740804a361bb28ad37cfe4edda8775a6ea96c38 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Mon, 25 Nov 2024 21:24:13 +0200 Subject: [PATCH] Make IgnoreEmptyCollectionsContractResolver special case ICollection.Count check (#1759) --- .../IgnoreEmptyCollectionsContractResolver.cs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/NJsonSchema/Infrastructure/IgnoreEmptyCollectionsContractResolver.cs b/src/NJsonSchema/Infrastructure/IgnoreEmptyCollectionsContractResolver.cs index c0edf2d38..132be39b0 100644 --- a/src/NJsonSchema/Infrastructure/IgnoreEmptyCollectionsContractResolver.cs +++ b/src/NJsonSchema/Infrastructure/IgnoreEmptyCollectionsContractResolver.cs @@ -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; }; }