Question

I want to send a C# 2 dimenssions string array to my JS client page.

server:

string[,] info = ib.GetInfo();
//info is [["string1","string2","string3"],["string4","string5","string6"]]

JavaScriptSerializer ser = new JavaScriptSerializer();           
return this.Content((new JavaScriptSerializer()).Serialize(info), "text/javascript");

ON the client JS side:

var mysr= JSON.parse(resp );

"string1","string2","string3","string4","string5","string6"

The result mysr is a 1 dimenssion array!

What is wrong? any help would be appreciated. The string can also contain quotes and double quotes

Was it helpful?

Solution

This is the way how JavaScriptSerializer works. See these codes

string[,] info1 = new string[2,3]{{"string1","string2","string3"},
                                  {"string4","string5","string6"}};
var json1 = new JavaScriptSerializer().Serialize(info1);

json => ["string1","string2","string3","string4","string5","string6"]

string[][] info2 = new string[][] { new[]{ "string1", "string2", "string3" }, 
                                    new[]{ "string4", "string5", "string6" } };
var json2 = new JavaScriptSerializer().Serialize(info2);

json => [["string1","string2","string3"],["string4","string5","string6"]]

if you can't change the return type of the method GetInfo(). I would suggest to use Json.Net

var json1 = JsonConvert.SerializeObject(info1);

It will return the json string as you expect.

OTHER TIPS

A multidimensional array is serialized as a one-dimensional array. You can use a jagged array instead of a two-dimensional array

You can also use Json.NET. Json.NET 4.5 Release 8 supports multidimensional arrays.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top