forked from JSONAPIdotNET/JSONAPI.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnumAttributeValueConverter.cs
More file actions
57 lines (53 loc) · 1.77 KB
/
Copy pathEnumAttributeValueConverter.cs
File metadata and controls
57 lines (53 loc) · 1.77 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
using System;
using System.Reflection;
using Newtonsoft.Json.Linq;
namespace JSONAPI.Core
{
/// <summary>
/// Implementation of <see cref="IAttributeValueConverter" /> suitable for
/// use converting between enum CLR properties and integer attributes.
/// </summary>
public class EnumAttributeValueConverter : IAttributeValueConverter
{
private readonly PropertyInfo _property;
private readonly Type _enumType;
private readonly bool _isNullable;
/// <summary>
/// Creates a new EnumAttributeValueConverter
/// </summary>
/// <param name="property"></param>
/// <param name="enumType"></param>
/// <param name="isNullable"></param>
public EnumAttributeValueConverter(PropertyInfo property, Type enumType, bool isNullable)
{
_property = property;
_enumType = enumType;
_isNullable = isNullable;
}
public JToken GetValue(object resource)
{
var value = _property.GetValue(resource);
if (value != null) return (int) value;
if (_isNullable) return null;
return 0;
}
public void SetValue(object resource, JToken value)
{
if (value == null || value.Type == JTokenType.Null)
{
if (_isNullable)
_property.SetValue(resource, null);
else
{
var enumValue = Enum.Parse(_enumType, "0");
_property.SetValue(resource, enumValue);
}
}
else
{
var enumValue = Enum.Parse(_enumType, value.ToString());
_property.SetValue(resource, enumValue);
}
}
}
}