forked from JSONAPIdotNET/JSONAPI.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectComplexAttributeValueConverter.cs
More file actions
39 lines (35 loc) · 1.26 KB
/
Copy pathObjectComplexAttributeValueConverter.cs
File metadata and controls
39 lines (35 loc) · 1.26 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
using System.Reflection;
using Newtonsoft.Json.Linq;
namespace JSONAPI.Core
{
/// <summary>
/// Implementation of <see cref="IAttributeValueConverter" /> suitable for
/// use with complex attributes that deserialize to custom types.
/// </summary>
public class ObjectComplexAttributeValueConverter : IAttributeValueConverter
{
private readonly PropertyInfo _property;
private readonly bool _isToMany;
/// <summary>
/// Creates a new ComplexAttributeValueConverter
/// </summary>
/// <param name="property"></param>
/// <param name="isToMany"></param>
public ObjectComplexAttributeValueConverter(PropertyInfo property, bool isToMany)
{
_property = property;
_isToMany = isToMany;
}
public JToken GetValue(object resource)
{
var value = _property.GetValue(resource);
if (value == null) return null;
return _isToMany ? (JToken)JArray.FromObject(value) : JObject.FromObject(value);
}
public void SetValue(object resource, JToken value)
{
var deserialized = value?.ToObject(_property.PropertyType);
_property.SetValue(resource, deserialized);
}
}
}