Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
148 changes: 7 additions & 141 deletions UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,9 @@
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.

using System;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnitsNet.Serialization.JsonNet.Internal;
using UnitsNet.Units;

namespace UnitsNet.Serialization.JsonNet
{
Expand All @@ -26,11 +22,6 @@ namespace UnitsNet.Serialization.JsonNet
/// </remarks>
public class UnitsNetJsonConverter : JsonConverter
{
/// <summary>
/// Numeric value field of a quantity, typically of type double or decimal.
/// </summary>
private const string ValueFieldName = "_value";

/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
Expand All @@ -46,29 +37,20 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
JsonSerializer serializer)
{
if (reader.ValueType != null)
{
return reader.Value;
}

object obj = TryDeserializeIComparable(reader, serializer);
// A null System.Nullable value or a comparable type was deserialized so return this
if (!(obj is ValueUnit vu))
{
return obj;
}

// "MassUnit.Kilogram" => "MassUnit" and "Kilogram"
string unitEnumTypeName = vu.Unit.Split('.')[0];
string unitEnumValue = vu.Unit.Split('.')[1];

// "MassUnit" => "Mass"
string quantityTypeName = unitEnumTypeName.Substring(0, unitEnumTypeName.Length - "Unit".Length);

// "UnitsNet.Units.MassUnit,UnitsNet"
string unitEnumTypeAssemblyQualifiedName = "UnitsNet.Units." + unitEnumTypeName + ",UnitsNet";

// "UnitsNet.Mass,UnitsNet"
string quantityTypeAssemblyQualifiedName = "UnitsNet." + quantityTypeName + ",UnitsNet";

// -- see http://stackoverflow.com/a/6465096/1256096 for details
Type unitEnumType = Type.GetType(unitEnumTypeAssemblyQualifiedName);
if (unitEnumType == null)
Expand All @@ -78,63 +60,10 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
throw ex;
}

Type quantityType = Type.GetType(quantityTypeAssemblyQualifiedName);
if (quantityType == null)
{
var ex = new UnitsNetException("Unable to find unit type.");
ex.Data["type"] = quantityTypeAssemblyQualifiedName;
throw ex;
}

double value = vu.Value;
object unitValue = Enum.Parse(unitEnumType, unitEnumValue); // Ex: MassUnit.Kilogram

return CreateQuantity(quantityType, value, unitValue);
}

/// <summary>
/// Creates a quantity (ex: Mass) based on the reflected quantity type, a numeric value and a unit value (ex: MassUnit.Kilogram).
/// </summary>
/// <param name="quantityType">Type of quantity, such as <see cref="Mass"/>.</param>
/// <param name="value">Numeric value.</param>
/// <param name="unitValue">The unit, such as <see cref="MassUnit.Kilogram"/>.</param>
/// <returns>The constructed quantity, such as <see cref="Mass"/>.</returns>
private static object CreateQuantity(Type quantityType, double value, object unitValue)
{
// We want the non-nullable return type, example candidates if quantity type is Mass:
// double Mass.From(double, MassUnit)
// double? Mass.From(double?, MassUnit)
MethodInfo notNullableFromMethod = quantityType
.GetDeclaredMethods()
.Single(m => m.Name == "From" && Nullable.GetUnderlyingType(m.ReturnType) == null);

// Of type QuantityValue
object quantityValue = GetFromMethodValueArgument(notNullableFromMethod, value);

// Ex: Mass.From(55, MassUnit.Gram)
// See ValueUnit about precision loss for quantities using decimal type.
return notNullableFromMethod.Invoke(null, new[] {quantityValue, unitValue});
}

/// <summary>
/// Returns numeric value wrapped as <see cref="QuantityValue"/>, based on the type of argument
/// of <paramref name="fromMethod"/>. Today this is always <see cref="QuantityValue"/>, but
/// we may extend to other types later such as QuantityValueDecimal.
/// </summary>
/// <param name="fromMethod">The reflected From(value, unit) method.</param>
/// <param name="value">The value to convert to the correct wrapper type.</param>
/// <returns></returns>
private static object GetFromMethodValueArgument(MethodInfo fromMethod, double value)
{
Type valueParameterType = fromMethod.GetParameters()[0].ParameterType;
if (valueParameterType == typeof(QuantityValue))
{
// We use this type that takes implicit cast from all number types to avoid explosion of method overloads that take a numeric value.
return (QuantityValue) value;
}
Enum unitValue = (Enum)Enum.Parse(unitEnumType, unitEnumValue); // Ex: MassUnit.Kilogram

throw new Exception(
$"The first parameter of the reflected quantity From() method was expected to be either UnitsNet.QuantityValue, but was instead {valueParameterType}.");
return Quantity.From(value, unitValue);
}

private static object TryDeserializeIComparable(JsonReader reader, JsonSerializer serializer)
Expand Down Expand Up @@ -182,74 +111,14 @@ public override void WriteJson(JsonWriter writer, object obj, JsonSerializer ser
return;
}

object quantityValue = GetValueOfQuantity(obj, quantityType); // double or decimal value
string quantityUnitName = GetUnitFullNameOfQuantity(obj, quantityType); // Example: "MassUnit.Kilogram"
IQuantity quantity = obj as IQuantity;

serializer.Serialize(writer, new ValueUnit
{
// See ValueUnit about precision loss for quantities using decimal type.
Value = Convert.ToDouble(quantityValue),
Unit = quantityUnitName
});
}

/// <summary>
/// Given quantity (ex: <see cref="Mass"/>), returns the full name (ex: "MassUnit.Kilogram") of the constructed unit given by the <see cref="Mass.Unit"/> property.
/// </summary>
/// <param name="obj">Quantity, such as <see cref="Mass"/>.</param>
/// <param name="quantityType">The type of <paramref name="obj"/>, passed in here to reuse a previous lookup.</param>
/// <returns>"MassUnit.Kilogram" for a mass quantity whose Unit property is MassUnit.Kilogram.</returns>
private static string GetUnitFullNameOfQuantity(object obj, Type quantityType)
{
// Get value of Unit property
PropertyInfo unitProperty = quantityType.GetProperty("Unit");
Enum quantityUnit = (Enum) unitProperty.GetValue(obj, null); // MassUnit.Kilogram

Type unitType = quantityUnit.GetType(); // MassUnit
return $"{unitType.Name}.{quantityUnit}"; // "MassUnit.Kilogram"
}

private static object GetValueOfQuantity(object value, Type quantityType)
{
FieldInfo valueField = GetPrivateInstanceField(quantityType, ValueFieldName);

// See ValueUnit about precision loss for quantities using decimal type.
object quantityValue = valueField.GetValue(value);
return quantityValue;
}

private static FieldInfo GetPrivateInstanceField(Type quantityType, string fieldName)
{
FieldInfo baseValueField;
try
{
baseValueField = quantityType
#if (NETSTANDARD1_0)
.GetTypeInfo()
.DeclaredFields
.Where(f => !f.IsPublic && !f.IsStatic)
#else
.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)
#endif
.SingleOrDefault(f => f.Name == fieldName);
}
catch (InvalidOperationException)
{
var ex = new UnitsNetException($"Expected exactly one private field named [{fieldName}], but found multiple.");
ex.Data["type"] = quantityType;
ex.Data["fieldName"] = fieldName;
throw ex;
}

if (baseValueField == null)
{
var ex = new UnitsNetException("No private fields found in type.");
ex.Data["type"] = quantityType;
ex.Data["fieldName"] = fieldName;
throw ex;
}

return baseValueField;
Value = quantity.Value,
Unit = $"{quantity.QuantityInfo.UnitType.Name}.{quantity.Unit}" // Example: "MassUnit.Kilogram"
} );
}

/// <summary>
Expand Down Expand Up @@ -280,9 +149,7 @@ private class ValueUnit
public override bool CanConvert(Type objectType)
{
if (IsNullable(objectType))
{
return CanConvertNullable(objectType);
}

return objectType.Namespace != null &&
(objectType.Namespace.Equals(nameof(UnitsNet)) ||
Expand Down Expand Up @@ -314,6 +181,5 @@ protected virtual bool CanConvertNullable(Type objectType)
}

#endregion

}
}
4 changes: 2 additions & 2 deletions UnitsNet.Tests/UnitConverterTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,9 @@ public void ConvertByAbbreviation_ConvertsTheValueToGivenUnit(double expectedVal

[Theory]
[InlineData(1, "UnknownQuantity", "m", "cm")]
public void ConvertByAbbreviation_ThrowsQuantityNotFoundExceptionOnUnknownQuantity(double inputValue, string quantityTypeName, string fromUnit, string toUnit)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, why was this test case removed? Is it no longer relevant/valid?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see further down why, but I think we can keep the test case and test for UnitNotFoundException instead?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It fails because it doesn't throw it any more 😃 Code is unnecessary.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But.. I honestly don't know what result to expect when calling this method with these arguments? What results are we getting if not exception?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will also give UnitNotFoundException. I'll add it back and catch that.

public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownQuantity( double inputValue, string quantityTypeName, string fromUnit, string toUnit)
{
Assert.Throws<QuantityNotFoundException>(() => UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit));
Assert.Throws<UnitNotFoundException>(() => UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit));
}

[Theory]
Expand Down
3 changes: 2 additions & 1 deletion UnitsNet/QuantityNotFoundException.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet.

using System;
Expand All @@ -9,6 +9,7 @@ namespace UnitsNet
/// Quantity type was not found. This is typically thrown for dynamic conversions,
/// such as <see cref="UnitConverter.ConvertByName" />.
/// </summary>
[Obsolete("")]
public class QuantityNotFoundException : UnitsNetException
{
/// <inheritdoc />
Expand Down
Loading