Wednesday, March 28, 2012

System.Json, .NET 4.5 and Dynamics

If you have used libraries like Json.Net or the DataContractSerializer or the JavaScriptSerializer, you already know that you would need a strong typed object for you to convert you class hiarachy into JSON. In a few cases this is frustrating.

In one of my earlier posts I talked about DynamicJson, this was an open source library (under MS-PL license) for you to create JSON counterparts from dynamic objects.

DynamicJson allows you to create JSON values from dynamic object, meaning you don’t really need to create a strong typed object, but create your JSON representation on the fly. >net 4.5 comes with a new namespace System.JSON, that exposes similar functionalities. You can try this out by installing System.Json from NuGet. It works seamlessly as .Net 4.5 is just a replacement for .NET 4.0.

So using System.Json, I can create JSON string like this…

dynamic book = new JsonObject();

book.BookName = "Asp.NET MVC";

book.Price = 123.45;

dynamic author = new JsonObject();

author.Name = "JKey Hay";

author.Age = 29;

book.Author = author;

A .ToString() on the book object would reveal the string…

{"BookName":"Asp.NET MVC","Price":123.45,"Author":{"Name":"JKey Hay","Age":29}}

On the other end, you can create a dynamic object from a JSON string like this…

dynamic parsedBook = JsonValue.Parse(str);

Console.WriteLine(parsedBook.BookName);

No comments:

Post a Comment