Turning JSON into a ExpandoObject

Recently I had the need for a web service of mine to take a JSON blob as an input. This isn’t really exciting or all that interesting a problem, but I really didn’t enjoy the code smell that came from drilling in to the resulting Dictionary object that comes from desterilizing the JSON object into something that .NET understands. public ActionResult Create() { IDictionary<string, object> request; using (var bodyStream = new StreamReader(Request.InputStream)) { var json = bodyStream.ReadToEnd(); JavaScriptSerializer ser = new JavaScriptSerializer(); request = ser.Deserialize<IDictionary<string, object>>(json); } var accountRequest = request["account"] as IDictionary<string, object>; var billingRequest = request["billing"] as IDictionary<string, object>; var billingInfoRequest = billingRequest["info"] as IDictionary<string, object>; var billingInvoiceRequest = billingRequest["invoice"] as IDictionary<string, object>; var billingItemsRequest = billingRequest["items"] as IDictionary<string, object>; // create account var account = new Account { CreatedOn = DateTime.UtcNow, Email = accountRequest["email"] as string, Name = accountRequest["company"] as string, UserName = request["user_name"] as string }; // ... more code using the dictionary object } After remembering that the ExpandoObject was also based on IDictionary<string, object> I thought it might be a marriage met in heaven. ...

July 19, 2010 · 4 min · 657 words · Nick Berardi