1

好吧,我不确定我问的问题是否正确,但这里是。我正在使用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 窗口显示对象看起来像这样 这 我的问题是我将如何访问item1from packlist.packs[0]

4

3 回答 3

4

您的 packlist 变量是具有单个键的字典,其值是对象数组,并且该数组中的每个条目也是字典。所以获得价值会是这样的。

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"
于 2012-05-28T22:22:07.703 回答
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 链接

http://msdn.microsoft.com/fr-fr/library/bb347013.aspx

于 2012-05-28T22:08:12.553 回答
0

我认为是这样:

var a = packlist.packs[0]["item1"];

于 2012-05-28T22:09:50.623 回答