C#处理Json的另外一种方式成功实践
程序员文章站
2024-03-05 13:52:12
作者在原文中说明了通过c#调用javascript来解析json字符串的方法。代码如下: 复制代码 代码如下: using microsoft.jscript; using...
作者在原文中说明了通过c#调用javascript来解析json字符串的方法。代码如下:
using microsoft.jscript;
using microsoft.vsa;
using microsoft.jscript.vsa;
public static dictionary<string, string> getmyvalue(string jsonsource, string key1, string key2)
{
dictionary<string, string> dic = new dictionary<string, string>();
string jsonstr = "function handlejson() {var j=" + jsonsource + ";var arr1=new array();var arr2=new array();for(var " + key2 + " in j." + key1 + ") arr1.push(" + key2 + "); return arr1;} handlejson(); ";
object o = eval.jscriptevaluate(jsonstr, vsaengine.createengine());
arrayobject arr = (arrayobject)o;
for (var i = 0; i <= (int)arr.length - 1; i++)
{
dic.add(arr[i].tostring(), arr[i].tostring());
}
return dic;
}
大致就是这个样子,通过c#调用js,用js解析json,并将返回值转换为c#数组。
复制代码 代码如下:
using microsoft.jscript;
using microsoft.vsa;
using microsoft.jscript.vsa;
public static dictionary<string, string> getmyvalue(string jsonsource, string key1, string key2)
{
dictionary<string, string> dic = new dictionary<string, string>();
string jsonstr = "function handlejson() {var j=" + jsonsource + ";var arr1=new array();var arr2=new array();for(var " + key2 + " in j." + key1 + ") arr1.push(" + key2 + "); return arr1;} handlejson(); ";
object o = eval.jscriptevaluate(jsonstr, vsaengine.createengine());
arrayobject arr = (arrayobject)o;
for (var i = 0; i <= (int)arr.length - 1; i++)
{
dic.add(arr[i].tostring(), arr[i].tostring());
}
return dic;
}
大致就是这个样子,通过c#调用js,用js解析json,并将返回值转换为c#数组。