-Fixed bug when converting an integer JValue to a nullable enum
This commit is contained in:
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user