7

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]]
sgtz
  • 8,849
  • 9
  • 51
  • 91

4 Answers4

11

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 ] ]
Timm
  • 2,652
  • 2
  • 25
  • 34
10

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.

Community
  • 1
  • 1
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
4

when you define an array like you did it isnt a matrix its the same array with two dimensions that why SerializeObject serialize it as the same array.

Liran
  • 591
  • 3
  • 13
  • +1... I'm thinking of a matrix and a 2d array as conceptually being the same thing... so I'm finding it hard to follow. You mean in terms of the underlying .net representation? – sgtz Nov 15 '11 at 16:25
1

I'm surprised it works at all. Json.NET doesn't support multidimensional arrays. Use a jagged array instead.

James Newton-King
  • 48,174
  • 24
  • 109
  • 130
  • Can you give any reason why it doesn't support this? Is it because of the ambiguity when converting back from JSON? – Timm Apr 21 '12 at 09:22