forked from JSONAPIdotNET/JSONAPI.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecimalAttributeValueConverter.cs
More file actions
54 lines (50 loc) · 1.74 KB
/
Copy pathDecimalAttributeValueConverter.cs
File metadata and controls
54 lines (50 loc) · 1.74 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
using System;
using System.Globalization;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace JSONAPI.Core
{
/// <summary>
/// Implementation of <see cref="IAttributeValueConverter" /> suitable for
/// use converting between decimal CLR properties and string attributes.
/// </summary>
public class DecimalAttributeValueConverter : IAttributeValueConverter
{
private readonly PropertyInfo _property;
/// <summary>
/// Creates a new DecimalAttributeValueConverter
/// </summary>
/// <param name="property"></param>
public DecimalAttributeValueConverter(PropertyInfo property)
{
_property = property;
}
public JToken GetValue(object resource)
{
var value = _property.GetValue(resource);
if (value == null) return null;
try
{
return ((Decimal)value).ToString(CultureInfo.InvariantCulture);
}
catch (InvalidCastException e)
{
throw new JsonSerializationException("Could not serialize decimal value.", e);
}
}
public void SetValue(object resource, JToken value)
{
if (value == null || value.Type == JTokenType.Null)
_property.SetValue(resource, null);
else
{
var stringTokenValue = value.Value<string>();
Decimal d;
if (!Decimal.TryParse(stringTokenValue, NumberStyles.Any, CultureInfo.InvariantCulture, out d))
throw new JsonSerializationException("Could not parse decimal value.");
_property.SetValue(resource, d);
}
}
}
}