简体   繁体   English

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

[英]How do I convert a c# two-dimensional array to a JSON object?

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. 在JSON对象中给出一个平面的一维数组。 The Microsoft documentation states: Microsoft文档说明:

'A multidimensional array is serialized as a one-dimensional array, and you should use it as a flat array.' '多维数组被序列化为一维数组,你应该将它用作平面数组。

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将其序列化为[[#,#,#,#],[#,#,#,#]等形式......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM