遍历包含多个ExpandoObject的ExpandoObject

3

我想知道是否可以遍历包含Expando对象数组的Expando对象?

我目前正在解析具有以下文件结构的一些JSON:

"event": 
     [{
    "name": "BEGIN!",
    "count": 1
}],
"context": 
     {
     "customer": {
        "greetings": 
          [
           {  "Value1": "Hello" },
           {  "Value2": "Bye" }
          ],
        "nicknames": []
    }
}

我可以通过以下方法获取“event”的扩展对象:

GenerateDictionary(((ExpandoObject[])dict["event"])[0], dict, "event_");

这是GenerateDictionary方法的代码:
private void GenerateDictionary(System.Dynamic.ExpandoObject output, Dictionary<string, object> dict, string parent)
    {
        try
        {
            foreach (var v in output)
            {
                string key = parent + v.Key;
                object o = v.Value;

                if (o.GetType() == typeof(System.Dynamic.ExpandoObject))
                {
                    GenerateDictionary((System.Dynamic.ExpandoObject)o, dict, key + "_");
                }
                else
                {
                    if (!dict.ContainsKey(key))
                    {
                        dict.Add(key, o);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            WritetoLog(itemname, ex);
        }
    }

我现在完全不知道如何检索'context_customer_greetings'中的所有值,因为当我尝试下面的操作时,它只会检索到'context_customer_greetings_value1'对象。

    GenerateDictionary(((System.Dynamic.ExpandoObject[])dict["context_customer_greetings"])[0], dict, "context_customer_greetings_");

能否遍历ExpandoObject?

希望我的问题表述清晰,谢谢你提前的帮助。


https://dev59.com/xsKCzogBFxS5KdRj3hgd - DLeh
请查看此问题的答案:https://dev59.com/HHE85IYBdhLWcg3w03Hz - Zharro
1个回答

1
我现在已经找到了一个解决方案(虽然很简单!)
我创建了一个新的动态对象,然后使用上述相同的方法对其进行迭代。
     dynamic s = dict["context_custom_greetings"];
     foreach(ExpandoObject o in s)
     {
        GenerateDictionary((ExpandoObject)o, dict, "context_custom_greetings_");
     }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接