From d26d54bd50579493c94df2f35c17cde1f3eb2718 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Fri, 24 Jul 2015 15:43:08 +1200 Subject: [PATCH] -Fixed serializing non-zero based multidimensional array --- .../JsonSerializerCollectionsTests.cs | 56 +++++++++++++++++++ .../JsonSerializerInternalWriter.cs | 2 +- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs index b5223cd5..ce4125d2 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerCollectionsTests.cs @@ -125,6 +125,62 @@ namespace Newtonsoft.Json.Tests.Serialization } #endif + [Test] + public void NonZeroBasedArray() + { + var onebasedArray = Array.CreateInstance(typeof(string), new[] { 3 }, new[] { 2 }); + + for (var i = onebasedArray.GetLowerBound(0); i <= onebasedArray.GetUpperBound(0); i++) + { + onebasedArray.SetValue(i.ToString(CultureInfo.InvariantCulture), new[] { i, }); + } + + string output = JsonConvert.SerializeObject(onebasedArray, Formatting.Indented); + + StringAssert.AreEqual(@"[ + ""2"", + ""3"", + ""4"" +]", output); + } + + [Test] + public void NonZeroBasedMultiArray() + { + // lets create a two dimensional array, each rank is 1-based of with a capacity of 4. + var onebasedArray = Array.CreateInstance(typeof(string), new[] { 3, 3 }, new[] { 1, 2 }); + + // Iterate of the array elements and assign a random double + for (var i = onebasedArray.GetLowerBound(0); i <= onebasedArray.GetUpperBound(0); i++) + { + for (var j = onebasedArray.GetLowerBound(1); j <= onebasedArray.GetUpperBound(1); j++) + { + onebasedArray.SetValue(i + "_" + j, new[] { i, j }); + } + } + + // Now lets try and serialize the Array + string output = JsonConvert.SerializeObject(onebasedArray, Formatting.Indented); + + StringAssert.AreEqual(@"[ + [ + ""1_2"", + ""1_3"", + ""1_4"" + ], + [ + ""2_2"", + ""2_3"", + ""2_4"" + ], + [ + ""3_2"", + ""3_3"", + ""3_4"" + ] +]", output); + } + [Test] public void MultiDObjectArray() { diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs index b22d03ce..c7f2d466 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs @@ -667,7 +667,7 @@ namespace Newtonsoft.Json.Serialization writer.WriteStartArray(); - for (int i = 0; i < values.GetLength(dimension); i++) + for (int i = values.GetLowerBound(dimension); i <= values.GetUpperBound(dimension); i++) { newIndices[dimension] = i; bool isTopLevel = (newIndices.Length == values.Rank);