Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add nested property to ExpandoObject

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.

like image 731
Alex Avatar asked Nov 30 '12 22:11

Alex


2 Answers

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";
like image 122
Roland Cooper Avatar answered Oct 04 '22 13:10

Roland Cooper


How about doing it like this:

var exo = new ExpandoObject() as IDictionary<String, Object>;
var nested1 = new ExpandoObject() as IDictionary<String, Object>;

exo.Add("Nested1", nested1);
nested1.Add("Nested2", "value");

dynamic d = exo;
Console.WriteLine(d.Nested1.Nested2); // Outputs "value"
like image 39
Mario S Avatar answered Oct 04 '22 14:10

Mario S