JSON.Net正确串行化的二维阵列,以一个一维阵列、正确、串行化、JSON

2023-09-04 09:06:48 作者:不单可以表达一个人的心情,也可以表现一个人的性格,很多人都喜

试图二维阵列转换成一个二维JSON.Net阵列。

时有什么错低于code?或者只是没有这种支持JSON.Net?

  VAR A =新的INT [2,4] {{1,1,1,1},{2,2,2,2}};

        Console.WriteLine(JsonConvert.SerializeObject(A));

        //控制台:[1,1,1,1,2,2,2,2]
        //
        //注意。显示一个一维阵列
        //而不是两个例如[[1,1,1,1],[2,2,2,2]]
 

解决方案

JavaScript没有一个二维数组在同一意义上,C#确实的概念。为了得到这样的描述的阵列here,你需要创建一个数组的数组来代替。

  //输出:[1,1,1,1],[2,2,2,2]
变种一个新= INT [] [] {新[] {1,1,1,1},新[] {2,2,2,2}};
 

更新:

JAVA语言基础 一维数组 二维数组

这听起来像 JSON.NET现在多维数组转换成JSON数组的数组,因此code。在OP,如果你使用了code以上将工作一样。

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]]

解决方案

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.