最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I convert a c# two-dimensional array to a JSON object? - Stack Overflow

programmeradmin0浏览0评论

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

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:

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

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

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:

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

Share Improve this question edited Sep 17, 2021 at 18:08 ruffin 17.5k10 gold badges95 silver badges149 bronze badges asked Aug 17, 2009 at 23:46 dandan 5,7849 gold badges47 silver badges59 bronze badges 1
  • Just for fun, I'll add that Newtonsoft's Json.NET doesn't have this serialization issue with two+-dimensional arrays and, to cover a popular use case in 2021, ASP.NET Core even provides a way to switch over – ruffin Commented Sep 24, 2021 at 14:21
Add a comment  | 

1 Answer 1

Reset to default 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...]

发布评论

评论列表(0)

  1. 暂无评论