简体   繁体   English

将C#二维数组格式化为Javascript

[英]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? 有没有一种更简单的方法可以将C#中的二维数组(例如[[1、2、3],[4、5、6]]转换为表示“ [[1、2、3],[4] ,5,6]]“,除了逐个增加每个值并手动添加语法之外?

I would like to use the array as an argument in my webView.ExecuteJavascript() method, which takes the method name string as an argument. 我想在我的webView.ExecuteJavascript()方法中将数组用作参数,该方法将方法名称字符串作为参数。 Ideally, in C#, it would look like 理想情况下,在C#中,它看起来像

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

The updateValues function in javascript looks like this javascript中的updateValues函数如下所示

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: 现在,结果存储在双精度数组列表(List)中,并以如下形式调用.ToArray()。ToString():

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

only gives me the variable type and not the actual values. 只给我变量类型而不是实际值。

Thanks 谢谢

You can use JavaScriptSerializer 您可以使用JavaScriptSerializer

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

or Json.Net Json.Net

string json = JsonConvert.SerializeObject(arr);

That way, you can convert almost any kind of object to json , not only arrays... 这样,您几乎可以将任何类型的对象都转换为json ,而不仅仅是数组...

You can use an expression like this to turn the list of arrays into the Javascript syntax: 您可以使用这样的表达式将数组列表转换为Javascript语法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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