Dynamic Object and JSON Serialization (C#)

Sometimes I make quick and dirty projects where I don't need solid models for everything. Sometimes my data is handled by the client-side code using Javascript and various frameworks like SignalR, JQuery or AngularJS.
In such cases I don't want to add stupid POCO objects just to handle JSON serialization and deserialization. Luckily I found dynamic objects and JSON.net to handle this tasks easily and quickly.

In case I need to send data to the client, I simply create an ExpandoObject (fount in .NET) and serialize it using Json.Net with "JsonConvert.SerializeObject()".

dynamic myObject = new ExpandoObject();
myObject.FavouriteDrink = "Beer";
myObject.ListenToMusic = true;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(myObject);

Output is something like: {\"FavouriteDrink\":\"Beer\", \"ListenToMusic\":true} Quick and dirty? I like it.

No comments:

Post a Comment