C# dynamic object and JSON serialization with Json.Net | thewayofcode



C# DYNAMIC OBJECT AND JSON SERIALIZATION WITH JSON.NET

Standard




4 VOTES
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.

Serialization

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:
1
2
3
dynamic foo = new ExpandoObject();
foo.Bar = "something";
string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo);
And here is the output:

“{\”Bar\”:\”something\”}”

Deserialization

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:
1
2
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.
Valerio

Комментарии