Monday, August 22, 2011

Jsonify an ExpandoObject in MVC3

I’ve recently stumbled across a scenario where it would make sense to use an ExpandoObject to populate an object which then would be serialized to JSON. But this cannot be done in MVC 3. The reason being that an ExpandoObject implements IDictionary<TKey, TValue>, and the JavaScriptSerializer interprets it as such, and results in the following output:


How to fix this? Well there is no easy way, and the the only way I could come up with are described in this StackOverflow post, How to flatten an ExpandoObject returned via JsonResult in MVC?. The post supplies us with to possibilities, an extension method to convert the ExpandoObject to a string, and a custom JsonConverter used only for ExpandoObjects.

All of these methods require that we client-side parses the JSON returned, using either eval(jsonString) or JSON.parse(jsonString) (preferred because of security issues). Not a nice way to do it, but of course the JavaScriptSerializer serializes a string as a JSON string, so this is currently the only way to do so.

You could implement a custom ActionResult, which removes the the start and end “, but then this method can only be used of non-string objects which would introduce a whole new set of problems.

No comments:

Post a Comment