I really like the ExpandoObject
while compiling a server-side dynamic object at runtime, but I am having trouble flattening this thing out during JSON serialization. First, I instantiate the object:
dynamic expando = new ExpandoObject();
var d = expando as IDictionary<string, object>;
expando.Add("SomeProp", SomeValueOrClass);
So far so good. In my MVC controller, I want to then send this down as a JsonResult, so I do this:
return new JsonResult(expando);
This serializes the JSON into the below, to be consumed by the browser:
[{"Key":"SomeProp", "Value": SomeValueOrClass}]
BUT, what I'd really like is to see this:
{SomeProp: SomeValueOrClass}
I know I can achieve this if I use dynamic
instead of ExpandoObject
-- JsonResult
is able to serialize the dynamic
properties and values into a single object (with no Key or Value business), but the reason I need to use ExpandoObject
is because I don't know all of the properties I want on the object until runtime, and as far as I know, I cannot dynamically add a property to a dynamic
without using an ExpandoObject
.
I may have to sift through the "Key", "Value" business in my javascript, but I was hoping to figure this out prior to sending it to the client. Thanks for your help!
Using JSON.NET you can call SerializeObject to "flatten" the expando object:
Will output:
In the context of an ASP.NET MVC Controller, the result can be returned using the Content-method:
I took the flattening process one step further and checked for list objects, which removes the key value nonsense. :)
I was able to solve this same problem using JsonFx.
output:
This is a late answer, but I had the same problem, and this question helped me solve them. As a summary, I thought I should post my results, in hopes that it speeds up the implementation for others.
First the ExpandoJsonResult, which you can return an instance of in your action. Or you can override the Json method in your controller and return it there.
Then the converter (which supports both serialization and de-serialization. See below for an example of how to de-serialize).
You can see in the ExpandoJsonResult class how to use it for serialization. To de-serialize, create the serializer and register the converter in the same way, but use
A big thank you, to all participants here that helped me.
I solved this by writing an extension method that converts the ExpandoObject into a JSON string:
This uses the excellent Newtonsoft library.
JsonResult then looks like this:
And this is returned to the browser:
And I can use it in javascript by doing this (referenced here):
I hope this helps!
I just had the same problem and figured out something pretty weird. If I do:
It works, but only if my method use HttpPost attribute. If I use HttpGet i get error. So my answer works only on HttpPost. In my case it was an Ajax Call so i could change HttpGet by HttpPost.