C# dynamic object and JSON serialization with Json.Net


Heads up!

The blog has moved!
If you are interested in reading new posts, the new URL to bookmark is http://blog.valeriogheri.com/


I’m working on a project where I don’t need a solid domain model as all the logic is handled by the client-side code using  javascript and various frameworks as SignalR, Knockout.js and jQuery.
That’s why I found myself unwilling to add dumb C# POCO objects just to handle JSON serialization and deserialization in the SignalR hub(s), and I turned to dynamic objects and Json.Net (starting from version 4.0)  to handle this tasks easily and quickly.


Let’s say that for example I want to send data to the browser. All I have to do is to create an ExpandoObject (my new favourite .Net class!) and serialize it using Json.Net “JsonConvert.SerializeObject()”.

Let’s see an example:

dynamic foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);

And here is the output:


Json.Net offers a great way to deserialize a JSON string into a dynamic using the JObject (you can find it under the Newtonsoft.Json.Linq namespace and here the details).

Let’s see an example re-using the previous foo object:

dynamic foo = JObject.Parse(jsonText);
string bar = foo.Bar; // bar = "something"

And that’s it, really easy and yet really powerful.
In a more structured application, I would probably not use this trick as I would probably have all of my ViewModels and Domain Models objects ready to use in type safe serialization/deserialization operations, but that’s not always the case.

I hope this helps.


9 thoughts on “C# dynamic object and JSON serialization with Json.Net

  1. You could use JObject rather than ExpandoObject just as easily. The minor advantage being that JObject is not sealed, so you’re free to sub-class it. In my experience, when you need specialised dynamic classes, anything that inherits from DynamicObject performs very poorly with JSON.net.

    • Hello thedorko, thanks for sharing your opinion!
      It’s true, I could have used JObject just as easily, but I was also interested in showing the amazing (at least in my opinion) ExpandoObject!
      About performance, as I said in the post, I would probably not follow this approach in a structured application that needs to squeeze every drop of performance out of eachline of code🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s