Remove json descriptor back to expando using JavaScriptSerializer?
I am creating a json object on the fly (no Json.net) via:
dynamic expando = new ExpandoObject();
expando.Age = 42;
expando.Name = "Royi";
expando.Childrens = new ExpandoObject();
expando.Childrens.First = "John";
What looks like:
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);
Result:
[{"Key":"Age","Value":42},{"Key":"Name","Value":"Royi"},{"Key":"Childrens","Value":[{"Key":"First","Value":"John"}]}]
Note that expando (which is an Idictionary of a string, object) stores data
Question
Now I want the string to deserialize back:
I tried:
var jsonDeserizlied = new JavaScriptSerializer().Deserialize<ExpandoObject>(jsonString);
But:
The type 'System.Dynamic.ExpandoObject' is not supported for array deserialization.
So how can I get
[{"Key":"Age","Value":42},{"Key":"Name","Value":"Royi"},{"Key":"Childrens","Value":[{"Key":"First","Value":"John"}]}]
go back to expanding the view?
p
we are not using JSON.net.
Update
I managed to change object[]
to IList<IDictionary<string,object>>
:
var jsonDeserizlied = new JavaScriptSerializer().Deserialize<IList<IDictionary<string,object>>>(jsonString);
What now:
but again I need to convert it to:
source to share
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);
Result:
Exactly what I wanted.
Console.WriteLine (tt.Age ); //52
source to share