diff --git a/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs index 94b89632..4cb64fe1 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JValueTests.cs @@ -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(); + Assert.AreEqual(StringComparison.OrdinalIgnoreCase, v.Value); + + v = JValue.CreateNull().ToObject(); + Assert.AreEqual(null, v); + + v = new JValue(5).ToObject(); + Assert.AreEqual(StringComparison.OrdinalIgnoreCase, v.Value); + + v = new JValue(20).ToObject(); + Assert.AreEqual((StringComparison)20, v.Value); + + v = new JValue(20).ToObject(); + Assert.AreEqual((StringComparison)20, v.Value); + + v = JsonConvert.DeserializeObject("20"); + Assert.AreEqual((StringComparison)20, v.Value); + + v = JsonConvert.DeserializeObject("20"); + Assert.AreEqual((StringComparison)20, v.Value); + } + [Test] public void FloatParseHandling() { diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index 4932eb87..769d050a 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -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); } }