From 4a74cf1b1a7511a177d967ac539b81b64ec7618e Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Sun, 22 Oct 2017 13:03:33 +1300 Subject: [PATCH] -Fixed deserializing with constructor and readonly collection property --- .../JsonSerializerCollectionsTests.cs | 33 +++++++++++++++++++ .../JsonSerializerInternalReader.cs | 2 +- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs index d15be75a..c9dde10e 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs @@ -2059,6 +2059,39 @@ namespace Newtonsoft.Json.Tests.Serialization } #endif + [Test] + public void DeserializeReadonlyArrayProperty() + { + string json = @"{""Endpoint"":""http://localhost"",""Name"":""account1"",""Dimensions"":[{""Key"":""Endpoint"",""Value"":""http://localhost""},{""Key"":""Name"",""Value"":""account1""}]}"; + + AccountInfo values = JsonConvert.DeserializeObject(json); + Assert.AreEqual("http://localhost", values.Endpoint); + Assert.AreEqual("account1", values.Name); + Assert.AreEqual(2, values.Dimensions.Length); + } + + public sealed class AccountInfo + { + private KeyValuePair[] metricDimensions; + + public AccountInfo(string endpoint, string name) + { + this.Endpoint = endpoint; + this.Name = name; + } + + public string Endpoint { get; } + + public string Name { get; } + + public KeyValuePair[] Dimensions => + this.metricDimensions ?? (this.metricDimensions = new KeyValuePair[] + { + new KeyValuePair("Endpoint", this.Endpoint.ToString()), + new KeyValuePair("Name", this.Name) + }); + } + public class MyClass : IList { private List _storage; diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index c7c528fa..414cfef0 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -2006,7 +2006,7 @@ namespace Newtonsoft.Json.Serialization { JsonArrayContract propertyArrayContract = (JsonArrayContract)propertyContract; - if (propertyArrayContract.CanDeserialize) + if (propertyArrayContract.CanDeserialize && !propertyArrayContract.IsReadOnlyOrFixedSize) { object createdObjectCollection = property.ValueProvider.GetValue(createdObject); if (createdObjectCollection != null)