3

I wondered if it is possible to iterate over an ExpandoObject that contains an array of Expando Objects?

I am currently parsing some JSON with a file structure like the below:

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

I can retrieve the expando object for 'event' by doing the following:

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

This is the code for the GenerateDictionary method:

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);
        }
    }

I am now totally stuck on how to retrieve all the values in 'context_customer_greetings' as when I attempt to do the below, it will only retrieve the object at context_customer_greetings_value1.

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

Is it possible to iterate through an ExpandoObject?

I hope this makes sense, thanking you in advance.

leppie
  • 115,091
  • 17
  • 196
  • 297

1 Answers1

1

I have now found a solution to this (albeit a simple one!)

I created a new dynamic object and then iterate across that using the same method above.

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