Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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.'

like image 326
dan Avatar asked Aug 17 '09 23:08

dan


People also ask

How do you convert AC to DC voltage?

The most common way to convert alternating current into direct current is to use one or more diodes, those handy electronic components that allow current to pass in one direction but not the other. Although a rectifier converts alternating current to direct current, the resulting direct current isn't a steady voltage.

Why do we convert AC to DC?

Storage: Direct current can be stored, whereas, alternating current cannot be. So in order to store electric energy, alternating current is converted into direct current. Due to the same reason digital devices also use direct current.

What is the process of converting AC power?

Rectification: The process of converting AC to DC is called rectification. The device used for rectification is called the rectifier.

What device converts AC to DC?

A rectifier is an electrical device that converts alternating current (AC), which periodically reverses direction, to direct current (DC), which flows in only one direction. The reverse operation is performed by the inverter.


1 Answers

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

like image 198
dan Avatar answered Oct 07 '22 23:10

dan