forked from angularsen/UnitsNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnitsNetBaseJsonConverter.cs
233 lines (205 loc) · 9.71 KB
/
UnitsNetBaseJsonConverter.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
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen ([email protected]). Maintained at https://github.com/angularsen/UnitsNet.
using System;
using System.Globalization;
using System.Linq;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace UnitsNet.Serialization.JsonNet
{
/// <summary>
/// Base converter for serializing and deserializing UnitsNet types to and from JSON.
/// Contains shared functionality used by <see cref="UnitsNetIQuantityJsonConverter"/> and <see cref="UnitsNetIComparableJsonConverter"/>
/// </summary>
/// <typeparam name="T">The type being converted. Should either be <see cref="IQuantity"/> or <see cref="IComparable"/></typeparam>
public abstract class UnitsNetBaseJsonConverter<T> : JsonConverter<T>
{
/// <summary>
/// Reads the "Unit" and "Value" properties from a JSON string
/// </summary>
/// <param name="jsonToken">The JSON data to read from</param>
/// <returns>A <see cref="ValueUnit"/></returns>
protected ValueUnit ReadValueUnit(JToken jsonToken)
{
if (!jsonToken.HasValues)
{
return null;
}
var jsonObject = (JObject) jsonToken;
var unit = jsonObject.GetValue(nameof(ValueUnit.Unit), StringComparison.OrdinalIgnoreCase);
var value = jsonObject.GetValue(nameof(ValueUnit.Value), StringComparison.OrdinalIgnoreCase);
var valueType = jsonObject.GetValue(nameof(ExtendedValueUnit.ValueType), StringComparison.OrdinalIgnoreCase);
var valueString = jsonObject.GetValue(nameof(ExtendedValueUnit.ValueString), StringComparison.OrdinalIgnoreCase);
if (unit == null || value == null)
{
return null;
}
if (valueType == null)
{
if (value.Type != JTokenType.Float && value.Type != JTokenType.Integer)
{
return null;
}
return new ValueUnit {Unit = unit.Value<string>(), Value = value.Value<double>()};
}
if (valueType.Type != JTokenType.String)
{
return null;
}
return new ExtendedValueUnit
{
Unit = unit.Value<string>(),
Value = value.Value<double>(),
ValueType = valueType.Value<string>(),
ValueString = valueString?.Value<string>()
};
}
/// <summary>
/// Convert a <see cref="ValueUnit"/> to an <see cref="IQuantity"/>
/// </summary>
/// <param name="valueUnit">The value unit to convert</param>
/// <exception cref="UnitsNetException">Thrown when an invalid Unit has been provided</exception>
/// <returns>An IQuantity</returns>
protected IQuantity ConvertValueUnit(ValueUnit valueUnit)
{
if (string.IsNullOrWhiteSpace(valueUnit?.Unit))
{
return null;
}
var unit = GetUnit(valueUnit.Unit);
return valueUnit switch
{
ExtendedValueUnit {ValueType: "decimal"} extendedValueUnit => Quantity.From(decimal.Parse(extendedValueUnit.ValueString, CultureInfo.InvariantCulture), unit),
_ => Quantity.From(valueUnit.Value, unit)
};
}
private static Enum GetUnit(string unit)
{
var unitParts = unit.Split('.');
if (unitParts.Length != 2)
{
var ex = new UnitsNetException($"\"{unit}\" is not a valid unit.");
ex.Data["type"] = unit;
throw ex;
}
// "MassUnit.Kilogram" => "MassUnit" and "Kilogram"
var unitEnumTypeName = unitParts[0];
var unitEnumValue = unitParts[1];
// "UnitsNet.Units.MassUnit,UnitsNet"
var unitEnumTypeAssemblyQualifiedName = "UnitsNet.Units." + unitEnumTypeName + ",UnitsNet";
// -- see http://stackoverflow.com/a/6465096/1256096 for details
var unitEnumType = Type.GetType(unitEnumTypeAssemblyQualifiedName);
if (unitEnumType == null)
{
var ex = new UnitsNetException("Unable to find enum type.");
ex.Data["type"] = unitEnumTypeAssemblyQualifiedName;
throw ex;
}
var unitValue = (Enum) Enum.Parse(unitEnumType, unitEnumValue); // Ex: MassUnit.Kilogram
return unitValue;
}
/// <summary>
/// Convert an <see cref="IQuantity"/> to a <see cref="ValueUnit"/>
/// </summary>
/// <param name="quantity">The quantity to convert</param>
/// <returns>A serializable object.</returns>
protected ValueUnit ConvertIQuantity(IQuantity quantity)
{
quantity = quantity ?? throw new ArgumentNullException(nameof(quantity));
if (quantity is IDecimalQuantity d)
{
return new ExtendedValueUnit
{
Unit = $"{quantity.QuantityInfo.UnitType.Name}.{quantity.Unit}",
Value = quantity.Value,
ValueString = d.Value.ToString(CultureInfo.InvariantCulture),
ValueType = "decimal"
};
}
return new ValueUnit {Value = quantity.Value, Unit = $"{quantity.QuantityInfo.UnitType.Name}.{quantity.Unit}"};
}
/// <summary>
/// Create a copy of a serializer, retaining any settings but leaving out a converter to prevent loops
/// </summary>
/// <param name="serializer">The serializer to copy</param>
/// <param name="currentConverter">The converter to leave out</param>
/// <returns>A serializer with the same settings and all converters except the current one.</returns>
protected JsonSerializer CreateLocalSerializer(JsonSerializer serializer, JsonConverter currentConverter)
{
var localSerializer = new JsonSerializer()
{
Culture = serializer.Culture,
CheckAdditionalContent = serializer.CheckAdditionalContent,
Context = serializer.Context,
ContractResolver = serializer.ContractResolver,
TypeNameHandling = serializer.TypeNameHandling,
TypeNameAssemblyFormatHandling = serializer.TypeNameAssemblyFormatHandling,
Formatting = serializer.Formatting,
ConstructorHandling = serializer.ConstructorHandling,
DateFormatHandling = serializer.DateFormatHandling,
DateFormatString = serializer.DateFormatString,
DateParseHandling = serializer.DateParseHandling,
DateTimeZoneHandling = serializer.DateTimeZoneHandling,
DefaultValueHandling = serializer.DefaultValueHandling,
EqualityComparer = serializer.EqualityComparer,
FloatFormatHandling = serializer.FloatFormatHandling,
FloatParseHandling = serializer.FloatParseHandling,
MaxDepth = serializer.MaxDepth,
MetadataPropertyHandling = serializer.MetadataPropertyHandling,
MissingMemberHandling = serializer.MissingMemberHandling,
NullValueHandling = serializer.NullValueHandling,
ObjectCreationHandling = serializer.ObjectCreationHandling,
PreserveReferencesHandling = serializer.PreserveReferencesHandling,
ReferenceLoopHandling = serializer.ReferenceLoopHandling,
ReferenceResolver = serializer.ReferenceResolver,
SerializationBinder = serializer.SerializationBinder,
StringEscapeHandling = serializer.StringEscapeHandling,
TraceWriter = serializer.TraceWriter
};
foreach (var converter in serializer.Converters.Where(x => x != currentConverter))
{
localSerializer.Converters.Add(converter);
}
return localSerializer;
}
/// <summary>
/// A structure used to serialize/deserialize Units.NET unit instances.
/// </summary>
protected class ValueUnit
{
/// <summary>
/// The unit of the value.
/// </summary>
/// <example>MassUnit.Pound</example>
/// <example>InformationUnit.Kilobyte</example>
[JsonProperty(Order = 1)]
public string Unit { get; [UsedImplicitly] set; }
/// <summary>
/// The value.
/// </summary>
[JsonProperty(Order = 2)]
public double Value { get; [UsedImplicitly] set; }
}
/// <summary>
/// A structure used to serialize/deserialize non-double Units.NET unit instances.
/// </summary>
/// <remarks>
/// This type was added for lossless serialization of quantities with <see cref="decimal"/> values.
/// The <see cref="decimal"/> type distinguishes between 100 and 100.00 but Json.NET does not, therefore we serialize decimal values as string.
/// </remarks>
protected sealed class ExtendedValueUnit : ValueUnit
{
/// <summary>
/// The value as a string.
/// </summary>
[JsonProperty(Order = 3)]
public string ValueString { get; [UsedImplicitly] set; }
/// <summary>
/// The type of the value, e.g. "decimal".
/// </summary>
[JsonProperty(Order = 4)]
public string ValueType { get; [UsedImplicitly] set; }
}
}
}