如何将c#二维数组转换为JSON对象?

时间:2022-07-05 21:19:32

If I have a two-dimensional array in C# - how can I convert it into a JSON string that contains a two dimensional array?

如果我在C#中有一个二维数组 - 我怎样才能将它转换为包含二维数组的JSON字符串?

eg.

例如。

int[,] numbers = new int[8,4];
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(numbers);

gives a flat one-dimensional array in a JSON object. The Microsoft documentation states:

在JSON对象中给出一个平面的一维数组。 Microsoft文档说明:

'A multidimensional array is serialized as a one-dimensional array, and you should use it as a flat array.'

'多维数组被序列化为一维数组,你应该将它用作平面数组。

1 个解决方案

#1


17  

You can use a jagged array instead of a two-dimensional array, which is defined like:

您可以使用锯齿状数组而不是二维数组,其定义如下:

int[][] numbers = new int[8][];

for (int i = 0; i <= 7; i++) {
   numbers[i] = new int[4];
   for (int j = 0; j <= 3; j++) {
      numbers[i][j] =i*j;
   }
}

The JavascriptSerializer will then serialise this into the form [[#,#,#,#],[#,#,#,#],etc...]

然后,JavascriptSerializer会将其序列化为[[#,#,#,#],[#,#,#,#]等形式......

#1


17  

You can use a jagged array instead of a two-dimensional array, which is defined like:

您可以使用锯齿状数组而不是二维数组,其定义如下:

int[][] numbers = new int[8][];

for (int i = 0; i <= 7; i++) {
   numbers[i] = new int[4];
   for (int j = 0; j <= 3; j++) {
      numbers[i][j] =i*j;
   }
}

The JavascriptSerializer will then serialise this into the form [[#,#,#,#],[#,#,#,#],etc...]

然后,JavascriptSerializer会将其序列化为[[#,#,#,#],[#,#,#,#]等形式......