【问题标题】:Iterate through an ExpandoObject that contains multiple ExpandoObjects遍历包含多个 ExpandoObject 的 ExpandoObject
【发布时间】:2015-07-08 09:17:01
【问题描述】:

我想知道是否可以迭代包含 Expando 对象数组的 ExpandoObject?

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

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

我可以通过执行以下操作来检索“事件”的扩展对象:

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?

我希望这是有道理的,提前谢谢你。

【问题讨论】:

标签: c# json expandoobject


【解决方案1】:

我现在已经找到了解决方案(虽然很简单!)

我创建了一个新的动态对象,然后使用上述相同的方法对其进行迭代。

     dynamic s = dict["context_custom_greetings"];
     foreach(ExpandoObject o in s)
     {
        GenerateDictionary((ExpandoObject)o, dict, "context_custom_greetings_");
     }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-04
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多