Getting dynamic ExpandoObject to serialize to JSON as expected

Serializing ExpandoObjects I am currently creating a JSON API for a handful of upcoming Sierra Trading Post projects. When I found myself generating JSON for a stripped-down representation of a number of domain classes, all wrapped with some metadata, I turned to dynamic and things have been going quite well. Unfortunately, there was a hurdle to getting the JSON to look the way I wanted. If you start playing around with serializing ExpandoObject to JSON, you will probably start finding a number of options. The easiest solution to find is the one that comes with .NET, JavaScriptSerializer under System.Web.Script.Serialization. It will happily serialize an ExpandoObject for you, but it probably won’t look the way you expect. Your searches will probably vary, but I found Newtonsoft’s JSON.NET, which handled ExpandoObject right out of the NuGet box. Then I stumbled on ServiceStack.Text (also “NuGettable”). While it does even weirder things than the .NET serializer with ExpandoObjects, it supposedly does them very fast. Test code dynamic test = new ExpandoObject(); test.x = “xvalue”; test.y = DateTime.Now; BCL JavaScriptSerializer (using System.Web.Script.Serialization;) JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string jsonOfTest = javaScriptSerializer.Serialize(test); // [{“Key”:”x”,”Value”:”xvalue”},{“Key”:”y”,”Value”:”\/Date(1314108923000)\/”}] Not quite what I was looking for but it makes sense if… Continue reading