-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));
}
[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]
public void FloatParseHandling()
{
+15 -6
View File
@@ -1714,16 +1714,25 @@ namespace Newtonsoft.Json.Linq
bool isEnum;
PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(objectType, out isEnum);
if (isEnum && Type == JTokenType.String)
if (isEnum)
{
Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType);
try
if (Type == JTokenType.String)
{
return Enum.Parse(enumType, (string)this, true);
Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType);
try
{
return Enum.Parse(enumType, (string) this, true);
}
catch (Exception ex)
{
throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string) this, enumType.Name), ex);
}
}
catch (Exception ex)
if (Type == JTokenType.Integer)
{
throw new ArgumentException("Could not convert '{0}' to {1}.".FormatWith(CultureInfo.InvariantCulture, (string)this, enumType.Name), ex);
Type enumType = objectType.IsEnum() ? objectType : Nullable.GetUnderlyingType(objectType);
return Enum.ToObject(enumType, ((JValue) this).Value);
}
}