-Fixed bug when converting an integer JValue to a nullable enum

This commit is contained in:
James Newton-King
2015-11-23 22:02:47 +13:00
parent a9c7d60d22
commit 2c3dafd62d
2 changed files with 40 additions and 6 deletions
@@ -69,6 +69,31 @@ namespace Newtonsoft.Json.Tests.Linq
Assert.AreEqual("undefined", v.ToString(Formatting.None)); Assert.AreEqual("undefined", v.ToString(Formatting.None));
} }
[Test]
public void ToObjectEnum()
{
StringComparison? v = new JValue("OrdinalIgnoreCase").ToObject<StringComparison?>();
Assert.AreEqual(StringComparison.OrdinalIgnoreCase, v.Value);
v = JValue.CreateNull().ToObject<StringComparison?>();
Assert.AreEqual(null, v);
v = new JValue(5).ToObject<StringComparison?>();
Assert.AreEqual(StringComparison.OrdinalIgnoreCase, v.Value);
v = new JValue(20).ToObject<StringComparison?>();
Assert.AreEqual((StringComparison)20, v.Value);
v = new JValue(20).ToObject<StringComparison>();
Assert.AreEqual((StringComparison)20, v.Value);
v = JsonConvert.DeserializeObject<StringComparison?>("20");
Assert.AreEqual((StringComparison)20, v.Value);
v = JsonConvert.DeserializeObject<StringComparison>("20");
Assert.AreEqual((StringComparison)20, v.Value);
}
[Test] [Test]
public void FloatParseHandling() public void FloatParseHandling()
{ {
+10 -1
View File
@@ -1714,7 +1714,9 @@ namespace Newtonsoft.Json.Linq
bool isEnum; bool isEnum;
PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(objectType, out isEnum); PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(objectType, out isEnum);
if (isEnum && Type == JTokenType.String) if (isEnum)
{
if (Type == JTokenType.String)
{ {
Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType); Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType);
try try
@@ -1727,6 +1729,13 @@ namespace Newtonsoft.Json.Linq
} }
} }
if (Type == JTokenType.Integer)
{
Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType);
return Enum.ToObject(enumType, ((JValue) this).Value);
}
}
switch (typeCode) switch (typeCode)
{ {
case PrimitiveTypeCode.BooleanNullable: case PrimitiveTypeCode.BooleanNullable: