Remove json descriptor back to expando using JavaScriptSerializer?

I am creating a json object on the fly (no via:

dynamic expando = new ExpandoObject();
expando.Age = 42;
expando.Name = "Royi";
expando.Childrens = new ExpandoObject();
expando.Childrens.First = "John"; 


What looks like:

enter image description here

So, I can query it like this:

Console.WriteLine (expando.Name); //Royi


So let's serialize it:

var jsonString = new JavaScriptSerializer().Serialize(expando);
Console.WriteLine (jsonString);





Note that expando (which is an Idictionary of a string, object) stores data


Now I want the string to deserialize back:

enter image description here

I tried:

var jsonDeserizlied = new JavaScriptSerializer().Deserialize<ExpandoObject>(jsonString);



The type 'System.Dynamic.ExpandoObject' is not supported for array deserialization.

So how can I get



go back to expanding the view?


we are not using


I managed to change object[]

to IList<IDictionary<string,object>>


 var jsonDeserizlied = new JavaScriptSerializer().Deserialize<IList<IDictionary<string,object>>>(jsonString);


What now:

enter image description here

but again I need to convert it to:

enter image description here


source to share

1 answer

Got it.

First, consider the fact that this is a IEnumerable<>

Json view (due to how it ExpandoObject

serializes through JavaScriptSerializer

), so:

var jsonDeserizlied = new   JavaScriptSerializer().Deserialize<IEnumerable<IDictionary<string,object>>>(jsonString);
 Console.WriteLine (jsonDeserizlied);


I also wrote this recursive function that reduces ExpandoObject

sub sub expandos recursively:

public ExpandoObject go( IEnumerable<IDictionary<string,object>> lst)

 return lst.Aggregate(new ExpandoObject(),
                           (aTotal,n) => {
                                (aTotal    as IDictionary<string, object>).Add(n["Key"].ToString(), n["Value"] is object[] ? go(  ((object[])n["Value"]).Cast<IDictionary<string,Object>>())  :n["Value"] );
                                return aTotal;



Yes, I know it can be improved, but I just want to show the idea.

So now we call it via:

var tt=   go(jsonDeserizlied);



enter image description here

Exactly what I wanted.

Console.WriteLine (tt.Age ); //52




All Articles