1

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

3
  • JSON.parse should be able to handle a 2-dimensional array without issue. I believe the problem lies in JavaScriptSerializer converting it to a 1-dimensional array. Commented Jan 16, 2014 at 17:51
  • Can you post how looks resp value on client? Commented Jan 16, 2014 at 17:53
  • I agree with @nderscore, this does sound like a problem with the way it is serialised. Can you verify that id.GetInfo(); returns string[,] and not string[][]. You'd most likely get an exception if this weren't the case, but just as a sanity check... Also, try to create a nested loop to convert string[,] into string[][] and try to serialise that, just to see what happens... Commented Jan 16, 2014 at 17:56

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I was typing my answer suggesting (trying) converting string[,] into string[][] when you posted this. Perfect timing :)
Indeed, i realized that [,] was wrong for JSON. Everything works as expected now. thanks so much! I just had to changed the return type of getinfo(). on JS client I still use JSON.parse(), eval works too.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.