JSON.Net incorrectly serializes two-dimensional array into one dimension

Trying to convert a two-dimensional array into a two-dimensional array of JSON.Net.

Is there something wrong with the code below? Or is it not supported by JSON.Net?

var A = new int[2, 4] { { 1, 1, 1, 1 }, { 2, 2, 2, 2 } }; Console.WriteLine(JsonConvert.SerializeObject(A)); // CONSOLE: [1,1,1,1,2,2,2,2] // // NB. displays a one dimensional array // instead of two eg [[1,1,1,1],[2,2,2,2]] 
+7
source share
4 answers

Javascript does not have the concept of a 2D array in the same sense as C #. To get an array like the one described here , you need to create an array of arrays.

 // output: [[1,1,1,1],[2,2,2,2]] var a = new int[][] { new[]{ 1, 1, 1, 1 }, new[]{ 2, 2, 2, 2 } }; 

Update:

This is similar to JSON.NET now converting multidimensional arrays into an array of arrays in JSON, so the code in OP will work just as if you were using the code above.

+8
source

Starting with Json.Net 4.5 Multidimensional Relase 8 arrays are supported .

So your example will work now and create the following JSON:

 [ [ 1, 1, 1, 1 ], [ 2, 2, 2, 2 ] ] 
+9
source

when you define an array, as you did, it is not a matrix, the same array with two dimensions why SerializeObject serializes it as the same array.

+4
source

I am surprised that it works at all. Json.NET does not support multidimensional arrays. Use a jagged array instead.

+1
source

All Articles