forked from openstacknetsdk/openstack.net
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathOpenStackContractResolver.cs
More file actions
67 lines (57 loc) · 2.44 KB
/
Copy pathOpenStackContractResolver.cs
File metadata and controls
67 lines (57 loc) · 2.44 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System;
using System.Collections;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace OpenStack.Serialization
{
/// <summary>
/// Provides the same serialization capabilities as json.net with some additions:
/// <para>* Ensures that empty enumerables are not serialized.</para>
/// </summary>
/// <exclude />
public class OpenStackContractResolver : DefaultContractResolver
{
/// <inheritdoc/>
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
DoNotSerializeEmptyLists(property);
return property;
}
private static void DoNotSerializeEmptyLists(JsonProperty property)
{
if (IsEnumerable(property))
{
PropertyInfo propertyInfo = property.DeclaringType.GetProperty(property.UnderlyingName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (propertyInfo == null) // We can't figure out what it's bound to, so don't modify it's serialization settings
return;
property.ShouldSerialize = containerInstance =>
{
var propertyValue = propertyInfo.GetValue(containerInstance);
return propertyValue != null && ((IEnumerable) propertyValue).OfType<object>().Any();
};
}
}
/// <inheritdoc/>
protected override JsonConverter ResolveContractConverter(Type objectType)
{
var converter = base.ResolveContractConverter(objectType);
var jsonConverterAttr = objectType.GetCustomAttribute<JsonConverterWithConstructorAttribute>(inherit:true);
if (jsonConverterAttr != null)
return jsonConverterAttr.CreateJsonConverterInstance();
return converter;
}
/// <summary>
/// Check if a property implements IEnumerable and IEnumerable<>
/// </summary>
private static bool IsEnumerable(JsonProperty property)
{
if (property.PropertyType == typeof (string))
return false;
var interfaces = property.PropertyType.GetInterfaces();
return interfaces.Any(i => i == typeof(IEnumerable));
}
}
}