diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue2954.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue2954.cs new file mode 100644 index 000000000..0aa60cebe --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue2954.cs @@ -0,0 +1,50 @@ +using System.Linq; +using Newtonsoft.Json.Linq; +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +using TestCase = Xunit.InlineDataAttribute; +#else +using NUnit.Framework; +#endif + +namespace Newtonsoft.Json.Tests.Issues +{ + public class Issue2954 + { + private const string JsonToTest = "{\"arg\": 1, \"field\": null, \"fieldEnum\": null}"; + + [Test] + //https://github.com/JamesNK/Newtonsoft.Json/issues/2954 + public void Test_Ignore_Null_Values() + { + var result = JsonConvert.DeserializeObject(JsonToTest, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); + + Assert.AreEqual(result.Field, 0); + Assert.AreEqual(result.FieldEnum, B.Option1); + } + + [Test] + public void Test_Throw_JsonSerializationException() + { + ExceptionAssert.Throws(() => JsonConvert.DeserializeObject(JsonToTest)); + } + + class A + { + public A(int arg) + { + } + + public int Field { get; set; } + public B FieldEnum { get; set; } + } + + enum B + { + Option1, + Option2, + } + } +} diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index 9fa364663..221e80848 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -975,6 +975,11 @@ private bool HasNoDefinedType(JsonContract? contract) return null; } + if (value == null && Serializer.NullValueHandling == NullValueHandling.Ignore) + { + return Activator.CreateInstance(targetType); + } + try { if (contract.IsConvertable)