From ce7f283b94c86341036078ed2f4e241b907b816d Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Mon, 12 Feb 2018 19:47:21 +1300 Subject: [PATCH] -Fixed bug when deserializing into existing non-IDictionary collection --- Src/Newtonsoft.Json.Tests/Issues/Issue0198.cs | 36 ++++++++++++++++++- .../JsonSerializerInternalReader.cs | 2 +- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue0198.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue0198.cs index 74b9632f..aace02b4 100644 --- a/Src/Newtonsoft.Json.Tests/Issues/Issue0198.cs +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue0198.cs @@ -34,6 +34,7 @@ using System.Reflection; using System.Runtime.Serialization; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; +using Newtonsoft.Json.Tests.TestObjects; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; @@ -48,7 +49,7 @@ namespace Newtonsoft.Json.Tests.Issues public class Issue0198 : TestFixtureBase { [Test] - public void Test() + public void Test_List() { IEnumerable objects = new List { @@ -96,6 +97,29 @@ namespace Newtonsoft.Json.Tests.Issues Assert.AreEqual(1, o.Prop3.Count); } + [Test] + public void Test_Collection() + { + TestClass3 c = new TestClass3(); + c.Prop1 = new Dictionary + { + ["key"] = "value" + }; + + string serializedData = JsonConvert.SerializeObject(c, new JsonSerializerSettings + { + TypeNameHandling = TypeNameHandling.All, + Formatting = Formatting.Indented + }); + + TestClass3 a = JsonConvert.DeserializeObject(serializedData, new JsonSerializerSettings + { + TypeNameHandling = TypeNameHandling.All + }); + + Assert.AreEqual(1, a.Prop1.Count); + } + class TestClass1 : AbstactClass { public TestClass1() @@ -118,6 +142,16 @@ namespace Newtonsoft.Json.Tests.Issues { public ICollection Prop3 { get; set; } = new List(); } + + class TestClass3 + { + public TestClass3() + { + Prop1 = new ModelStateDictionary(); + } + + public IDictionary Prop1 { get; set; } + } } } #endif \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index 39b2e585..a37888f3 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -557,7 +557,7 @@ namespace Newtonsoft.Json.Serialization } else { - targetDictionary = PopulateDictionary(dictionaryContract.ShouldCreateWrapper ? dictionaryContract.CreateWrapper(existingValue) : (IDictionary)existingValue, reader, dictionaryContract, member, id); + targetDictionary = PopulateDictionary(dictionaryContract.ShouldCreateWrapper || !(existingValue is IDictionary) ? dictionaryContract.CreateWrapper(existingValue) : (IDictionary)existingValue, reader, dictionaryContract, member, id); } return targetDictionary;