Created
January 15, 2020 20:48
-
-
Save maxfridbe/d980149584313596f4d03e84c78bc5e4 to your computer and use it in GitHub Desktop.
will serialize only not null or empty lists
This file contains hidden or 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
public class ShouldSerializeContractResolver : DefaultContractResolver | |
{ | |
public static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver(); | |
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) | |
{ | |
JsonProperty property = base.CreateProperty(member, memberSerialization); | |
if (property.PropertyType == typeof(string)) | |
return property; | |
if (!property.PropertyType.IsGenericType) | |
return property; | |
var pname = property.UnderlyingName;//.PropertyName; | |
var genericTypeDefinition = property.PropertyType.GetGenericTypeDefinition(); | |
if (genericTypeDefinition.GetInterfaces() | |
.Any(t => t.IsGenericType && | |
t.GetGenericTypeDefinition() == typeof(IEnumerable<>))) | |
{ | |
property.ShouldSerialize = | |
instance => | |
{ | |
var x = member; | |
if (instance == null) | |
return false; | |
object v; | |
switch (member) | |
{ | |
case FieldInfo fieldInfo: | |
v = fieldInfo.GetValue(instance); | |
break; | |
case PropertyInfo propertyInfo: | |
v= propertyInfo.GetValue(instance); | |
break; | |
default: | |
return true; | |
} | |
var lst = v as IEnumerable<object>; | |
if (lst == null) | |
return false; | |
return lst.Any(); | |
}; | |
} | |
return property; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment