Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.Net incorrectly serializes a two dimensional array to a one dimension

Tags:

c#

.net

json.net

Trying to convert a two dimensional array to a two dimensional JSON.Net array.

Is there something wrong with the code below? Or just isn't this 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 e.g. [[1,1,1,1],[2,2,2,2]]
like image 678
sgtz Avatar asked Nov 15 '11 16:11

sgtz


2 Answers

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

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

[ [ 1, 1, 1, 1 ], [ 2, 2, 2, 2 ] ]
like image 121
Timm Avatar answered Sep 18 '22 13:09

Timm


Javascript doesn't have the notion of a 2D array in the same sense that C# does. In order to get an array like that described here, you'll need to create an array of arrays instead.

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

Update:

It sounds like JSON.NET now converts multidimensional arrays into an array of arrays in JSON, so the code in the OP will work the same as if you used the code above.

like image 31
StriplingWarrior Avatar answered Sep 18 '22 13:09

StriplingWarrior