Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modified serilization to support units saved as IComparable #200

Merged
merged 5 commits into from
Nov 2, 2016
Merged
Show file tree
Hide file tree
Changes from 3 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
174 changes: 174 additions & 0 deletions UnitsNet.Serialization.JsonNet.Tests/UnitsNetJsonConverterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
using System;
using Newtonsoft.Json;
using NUnit.Framework;
using System.Collections.Generic;

namespace UnitsNet.Serialization.JsonNet.Tests
{
Expand Down Expand Up @@ -226,12 +227,185 @@ public void UnitEnumChangedAfterSerialization_ExpectUnitCorrectlyDeserialized()
// still deserializable, and the correct value of 1000 g is obtained.
Assert.That(deserializedMass.Grams, Is.EqualTo(1000));
}

[Test]
public void UnitInIComparable_ExpectUnitCorrectlyDeserialized()
{
TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable()
{
Value = Power.FromWatts(10)
};
JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettigns();

string json = JsonConvert.SerializeObject(testObjWithIComparable,jsonSerializerSettings);
Copy link
Owner

Choose a reason for hiding this comment

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

Add space between params.


var deserializedTestObject = JsonConvert.DeserializeObject<TestObjWithIComparable>(json,jsonSerializerSettings);

Assert.That(deserializedTestObject.Value.GetType(), Is.EqualTo(typeof(Power)));
Assert.That((Power)deserializedTestObject.Value, Is.EqualTo(Power.FromWatts(10)));
}

[Test]
public void DoubleInIComparable_ExpectUnitCorrectlyDeserialized()
{
TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable()
{
Value = 10.0
};
JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettigns();

string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings);

var deserializedTestObject = JsonConvert.DeserializeObject<TestObjWithIComparable>(json, jsonSerializerSettings);

Assert.That(deserializedTestObject.Value.GetType(), Is.EqualTo(typeof(double)));
Assert.That((double)deserializedTestObject.Value, Is.EqualTo(10.0));
}

[Test]
public void ClassInIComparable_ExpectUnitCorrectlyDeserialized()
{
TestObjWithIComparable testObjWithIComparable = new TestObjWithIComparable()
{
Value = new ComparableClass() { Value = 10 }
};
JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettigns();

string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings);
var deserializedTestObject = JsonConvert.DeserializeObject<TestObjWithIComparable>(json, jsonSerializerSettings);

Assert.That(deserializedTestObject.Value.GetType(), Is.EqualTo(typeof(ComparableClass)));
Assert.That(((ComparableClass)(deserializedTestObject.Value)).Value, Is.EqualTo(10.0));
}

[Test]
public void OtherObjectWithUnitAndValue_ExpectCorrectResturnValues()
{
TestObjWithValueAndUnit testObjWithValueAndUnit = new TestObjWithValueAndUnit()
{
Value = 5,
Unit = "Test",
};
JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettigns();

string json = JsonConvert.SerializeObject(testObjWithValueAndUnit, jsonSerializerSettings);
TestObjWithValueAndUnit deserializedTestObject = JsonConvert.DeserializeObject<TestObjWithValueAndUnit>(json, jsonSerializerSettings);

Assert.That(deserializedTestObject.Value.GetType(), Is.EqualTo(typeof(double)));
Assert.That(deserializedTestObject.Value, Is.EqualTo(5.0));
Assert.That(deserializedTestObject.Unit, Is.EqualTo("Test"));
}

[Test, TestCaseSource(nameof(TestObjectsForThreeObjectsInIComparableWithDifferentValues_ExpectAllCorrectlyDeserialized))]
Copy link
Owner

Choose a reason for hiding this comment

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

This part was slightly confusing to me, as I haven't used TestCaseSource before. If there is only one case, I think I would prefer a normal method that give me that TestObjWithThreeIComparable object.

Copy link
Contributor Author

@eriove eriove Nov 1, 2016

Choose a reason for hiding this comment

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

This will actually be 27 tests (testing all combinations of objects). Might be a little too much. I started with 3 very similar tests and did this to reduce code duplication and then it was easy to add the loop with all combinations. I have to admit that I don't fully understand the serialization so I rather have some extra tests just to be sure.

Copy link
Owner

@angularsen angularsen Nov 2, 2016

Choose a reason for hiding this comment

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

Ah, ok. 27 tests seem a bit overboard, yes. Tests are nice, but I want each test to bring value and from the way I understand the implementation design and the test, I don't see how testing multiple variations of TestObjWithThreeIComparable will help us avoid bugs here. I think I'd rather have one or possibly two test cases with different combinations, but that should be quite enough, I think.

Their docs helped me understand what goes on: http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_TypeNameHandling.htm

Basically they add a $type prop that describes the actual object type when it was serialized, then the deserializer tries to use the exact same type by its assembly name, and full type name.

Copy link
Owner

Choose a reason for hiding this comment

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

public void ThreeObjectsInIComparableWithDifferentValues_ExpectAllCorrectlyDeserialized(
IComparable comparable1,
IComparable comparable2,
IComparable comparable3)
{
TestObjWithThreeIComparable testObjWithIComparable = new TestObjWithThreeIComparable()
{
Value1 = comparable1,
Value2 = comparable2,
Value3 = comparable3,
};
JsonSerializerSettings jsonSerializerSettings = CreateJsonSerializerSettigns();

string json = JsonConvert.SerializeObject(testObjWithIComparable, jsonSerializerSettings);
var deserializedTestObject = JsonConvert.DeserializeObject<TestObjWithThreeIComparable>(json, jsonSerializerSettings);

Assert.That(deserializedTestObject.Value1.GetType(), Is.EqualTo(comparable1.GetType()));
Assert.That(((deserializedTestObject.Value1)), Is.EqualTo(comparable1));
Copy link
Owner

Choose a reason for hiding this comment

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

Redundant parantheses.

Assert.That(deserializedTestObject.Value2.GetType(), Is.EqualTo(comparable2.GetType()));
Assert.That(((deserializedTestObject.Value2)), Is.EqualTo(comparable2));
Assert.That(deserializedTestObject.Value3.GetType(), Is.EqualTo(comparable3.GetType()));
Assert.That(((deserializedTestObject.Value3)), Is.EqualTo(comparable3));
}

public static object[] TestObjectsForThreeObjectsInIComparableWithDifferentValues_ExpectAllCorrectlyDeserialized
Copy link
Owner

Choose a reason for hiding this comment

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

Can be private.

{
get
{
List<object> result = new List<object>();
var objects = new object[] { 10.0, Power.FromWatts(19), new ComparableClass() { Value = 10 } };
for (int i = 0; i < objects.Length; i++)
{
for (int j = 0; j < objects.Length; j++)
{
for (int k = 0; k < objects.Length; k++)
{
result.Add(new object[] { objects[i], objects[j], objects[k]});
}
}
}
return result.ToArray();
}
}

private static JsonSerializerSettings CreateJsonSerializerSettigns()
Copy link
Owner

Choose a reason for hiding this comment

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

Typo

{
var jsonSerializerSettings = new JsonSerializerSettings()
{
Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.Auto
};
jsonSerializerSettings.Converters.Add(new UnitsNetJsonConverter());
return jsonSerializerSettings;
}
}

internal class TestObj
{
public Frequency? NullableFrequency { get; set; }
public Frequency NonNullableFrequency { get; set; }
}

internal class TestObjWithValueAndUnit : IComparable
Copy link
Owner

Choose a reason for hiding this comment

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

All these types can be private, can't they?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That's true. Followed the existing class, will change all of them.

{
public double Value { get; set; }
public string Unit { get; set; }

public int CompareTo(object obj)
{
return Value.CompareTo(obj);
}
}

internal class ComparableClass : IComparable
{
public int Value { get; set; }
public int CompareTo(object obj)
{
return Value.CompareTo(obj);
}

// Needed for virfying that the deserialized object is the same, should not affect the serilization code
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return Value.Equals(((ComparableClass)obj).Value);
}

public override int GetHashCode()
{
return Value.GetHashCode();
}
}

internal class TestObjWithIComparable
{
public IComparable Value { get; set; }
}

internal class TestObjWithThreeIComparable
{
public IComparable Value1 { get; set; }

public IComparable Value2 { get; set; }

public IComparable Value3 { get; set; }
}
}
}
57 changes: 51 additions & 6 deletions UnitsNet.Serialization.JsonNet/UnitsNetJsonConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
using System.Reflection;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace UnitsNet.Serialization.JsonNet
{
Expand Down Expand Up @@ -55,10 +56,17 @@ public class UnitsNetJsonConverter : JsonConverter
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var vu = serializer.Deserialize<ValueUnit>(reader);
// A null System.Nullable value was deserialized so just return null.
if (reader.ValueType != null)
{
return reader.Value;
}
object obj = TryDeserializeIComparable(reader, serializer);
var vu = obj as ValueUnit;
// A null System.Nullable value or a comparable type was deserialized so return this
if (vu == null)
return null;
{
return obj;
}

// "MassUnit.Kilogram" => "MassUnit" and "Kilogram"
string unitEnumTypeName = vu.Unit.Split('.')[0];
Expand Down Expand Up @@ -102,10 +110,31 @@ where m.Name.Equals("From", StringComparison.InvariantCulture) &&
// TODO: there is a possible loss of precision if base value requires higher precision than double can represent.
// Example: Serializing Information.FromExabytes(100) then deserializing to Information
// will likely return a very different result. Not sure how we can handle this?
return fromMethod.Invoke(null, BindingFlags.Static, null, new[] {vu.Value, unit},
return fromMethod.Invoke(null, BindingFlags.Static, null, new[] { vu.Value, unit },
CultureInfo.InvariantCulture);
}

private static object TryDeserializeIComparable(JsonReader reader, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (!token.HasValues || token[nameof(ValueUnit.Unit)] == null || token[nameof(ValueUnit.Value)] == null)
{
JsonSerializer localSerializer = new JsonSerializer()
{
TypeNameHandling = serializer.TypeNameHandling,
};
return token.ToObject<IComparable>(localSerializer);
}
else
{
return new ValueUnit()
{
Unit = token[nameof(ValueUnit.Unit)].ToString(),
Value = token[nameof(ValueUnit.Value)].ToObject<double>()
};
}
}

/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
Expand All @@ -117,6 +146,18 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s
{
Type unitType = value.GetType();

// ValueUnit should be written as usual (but read in a custom way)
if(unitType == typeof(ValueUnit))
{
JsonSerializer localSerializer = new JsonSerializer()
{
TypeNameHandling = serializer.TypeNameHandling,
};
JToken t = JToken.FromObject(value, localSerializer);

t.WriteTo(writer);
return;
}
FieldInfo[] fields =
unitType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
if (fields.Length == 0)
Expand Down Expand Up @@ -184,7 +225,11 @@ public override bool CanConvert(Type objectType)
return CanConvertNullable(objectType);
}

return objectType.Namespace != null && objectType.Namespace.Equals("UnitsNet");
return objectType.Namespace != null &&
(objectType.Namespace.Equals(nameof(UnitsNet)) ||
objectType == typeof(ValueUnit) ||
// All unit types implement IComparable
objectType == typeof(IComparable));
}

/// <summary>
Expand All @@ -206,7 +251,7 @@ protected virtual bool CanConvertNullable(Type objectType)
{
// Need to look at the FullName in order to determine if the nullable type contains a UnitsNet type.
// For example: FullName = 'System.Nullable`1[[UnitsNet.Frequency, UnitsNet, Version=3.19.0.0, Culture=neutral, PublicKeyToken=null]]'
return objectType.FullName != null && objectType.FullName.Contains("UnitsNet.");
return objectType.FullName != null && objectType.FullName.Contains(nameof(UnitsNet) + ".");
}

#endregion
Expand Down