-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathShouldSerializeListContractResolver.cs
33 lines (29 loc) · 1.22 KB
/
ShouldSerializeListContractResolver.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System;
using System.Collections;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Pyrus.ApiClient.JsonConverters
{
internal class ShouldSerializeListContractResolver : DefaultContractResolver
{
public static readonly ShouldSerializeListContractResolver Instance = new ShouldSerializeListContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
var isDefaultValueIgnored = ((property.DefaultValueHandling ?? DefaultValueHandling.Ignore) & DefaultValueHandling.Ignore) != 0;
if (isDefaultValueIgnored && !typeof(string).IsAssignableFrom(property.PropertyType) && typeof(IEnumerable).IsAssignableFrom(property.PropertyType))
{
bool NewShouldSerialize(object obj)
{
return !(property.ValueProvider.GetValue(obj) is ICollection collection) || collection.Count != 0;
}
var oldShouldSerialize = property.ShouldSerialize;
property.ShouldSerialize = oldShouldSerialize != null
? o => oldShouldSerialize(o) && NewShouldSerialize(o)
: (Predicate<object>) NewShouldSerialize;
}
return property;
}
}
}