简体   繁体   中英

Formatting C# two dimensional array to Javascript

Is there a simpler way of converting a two dimensional array in C#, such as [[1, 2, 3],[4, 5, 6]] into a string that says "[[1, 2, 3],[4, 5, 6]]", other than incrementing through each value and adding in the syntax manually?

I would like to use the array as an argument in my webView.ExecuteJavascript() method, which takes the method name string as an argument. Ideally, in C#, it would look like

webView.ExecuteJavascript("updateValues([[1, 2, 3],[4, 5, 6]])")

The updateValues function in javascript looks like this

updateValues(newvalues) {
oldvalues = newvalues
}

Would there be an easier way to do this? Right now, the results are stored in a list of double arrays (List), and calling .ToArray().ToString(), in a form such as this:

webView.ExecuteJavascript("updateValues(" + gaugeCol.ToArray().ToString() + ")");

only gives me the variable type and not the actual values.

Thanks

You can use JavaScriptSerializer

var arr = new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } };
string json = new JavaScriptSerializer().Serialize(arr); 

or Json.Net

string json = JsonConvert.SerializeObject(arr);

That way, you can convert almost any kind of object to json , not only arrays...

You can use an expression like this to turn the list of arrays into the Javascript syntax:

"[" + String.Join(",", gaugeCol.Select(g =>
  "[" + String.Join(",", Array.ConvertAll(g, Convert.ToString)) + "]"
)) + "]"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM