好吧,我不确定我是否在问正确的问题,但是这里有。我正在使用Javascript .NET来解析Javascript对象数组。我的代码看起来像这样:
object packlist;
using (var context = new JavascriptContext())
{
context.Run(@"function packlist() { this.packs = new Array(); }
var packlist = new packlist();
packlist.packs[0] = { item1:""something"", item2:""something2"", item3:""something3"" };
packlist.packs[1] = { item1:""something"", item2:""something2"", item3:""something3"" };
packlist.packs[2] = { item1:""something"", item2:""something2"", item3:""something3"" };");
packlist = context.GetParameter("packlist");
}
调试时,Locals窗口显示对象看起来像this
我的问题是如何从item1
访问packlist.packs[0]
?
答案 0 :(得分:4)
您的packlist变量是一个包含单个键的Dictionary,其值为object-array,该数组中的每个条目也都是Dictionary。所以获得价值将会是这样的。
Dictionary<string,object> dicPacklist =(Dictionary<string,object>) packlist;
object[] packs = (object[])dicPacklist["packs"];
Dictionary<string,object> dicPackOne = (Dictionary<string,object>)packs[0];
object item1Value = dicPackOne["item1"]; //"something"
答案 1 :(得分:3)
一般结构如下:
PackList => Dictionary of <string, Dictionary<string,object>[]>
这意味着它是一个字典,其中每个值都是字典的结构。
应该是
object[] arr = packlist["packs"] as object[];
Dictionary<string, object> dictPack = arr[0] as Dictionary<string, object>;
object item1 = dictPack["item1"];
或
object packs;
if (packlist.TryGetValue("packs",out packs)) {
object[] arr = packs as object[];
Dictionary<string, object> dictPack = arr[0] as Dictionary<string, object>;
object item1 = dictPack["item1"];
}
它们之间的区别在于,在第一个中,假设密钥存在于字典中,否则它会抛出异常。在第二个中,它将尝试获取值并告诉您密钥是否有效。
要检查字符是否在字典中,您可以使用:
bool exists = packlist.ContainsKey("item1");
浏览词典中的所有项目
foreach KeyPairValue<string,object> kp in packlist
{
string key = kp.Key;
object value = kp.Value;
}
这是字典类的MSDN链接
答案 2 :(得分:0)
我认为是:
var a = packlist.packs [0] [“item1”];