问题
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]]
回答1:
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.
回答2:
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 ] ]
回答3:
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.
回答4:
I'm surprised it works at all. Json.NET doesn't support multidimensional arrays. Use a jagged array instead.
来源:https://stackoverflow.com/questions/8139265/json-net-incorrectly-serializes-a-two-dimensional-array-to-a-one-dimension