Forked from ejsmith/EmptyCollectionContractResolver.cs
Created
February 26, 2018 13:25
-
-
Save tugcearar/91285944eb011da875df07939026400f to your computer and use it in GitHub Desktop.
EmptyCollectionContractResolver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class EmptyCollectionContractResolver : DefaultContractResolver { | |
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { | |
JsonProperty property = base.CreateProperty(member, memberSerialization); | |
Predicate<object> shouldSerialize = property.ShouldSerialize; | |
property.ShouldSerialize = obj => (shouldSerialize == null || shouldSerialize(obj)) && !IsEmptyCollection(property, obj); | |
return property; | |
} | |
private bool IsEmptyCollection(JsonProperty property, object target) { | |
var value = property.ValueProvider.GetValue(target); | |
var collection = value as ICollection; | |
if (collection != null && collection.Count == 0) | |
return true; | |
if (!typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) | |
return false; | |
var countProp = property.PropertyType.GetProperty("Count"); | |
if (countProp == null) | |
return false; | |
var count = (int)countProp.GetValue(value, null); | |
return count == 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment