Dynamically add nested property to ExpandoObject

Alex picture Alex · Nov 30, 2012 · Viewed 7.2k times · Source

I'm getting a JSON object (may contain multiple levels of JSON arrays and such) which I want to translate into an ExpandoObject.

I figured out how to add simple properties to an ExpandoObject at runtime as it implements IDictionary, but how do I add nested properties (for example, something like myexpando.somelist.anotherlist.someitem) at runtime that will resolve correctly?

Edit: Currently this works for simple (first level) properties well:

var exo = new ExpandoObject() as IDictionary<String, Object>;
exo.Add(name, value);

The question is how to get the name to be nested and the ExpandoObject to resolve accordingly.

Answer

Roland Cooper picture Roland Cooper · Jul 9, 2014
dynamic myexpando = new ExpandoObject();
myexpando.somelist = new ExpandoObject() as dynamic;
myexpando.somelist.anotherlist = new ExpandoObject() as dynamic;
myexpando.somelist.anotherlist.someitem = "Hey Hey There! I'm a nested value :D";