JsonToDynamic: Consuming Json Data as Dynamic Objects in C# 4.0

About a month ago I was reading the early access edition of C# in Depth, Second Edition from Jon Skeet. In this book the auto demonstrates using dynamic objects and the dynamic keyword in C# using a wrapper around an xml document. Suppose you have a xml document containing a number of books

<book>
	<autor>The Autor</autor>
</boo>

Now you can access the auto properties of each book in the following way:

dynamic book = GetBookAsDynamic();
string autoName = book.autor

Having been using Json intensively  the last few weeks and seeing how easy it is to consume Json in JavaScript, I thought dynamic object would be a fantastic way to make Json more natural in the .Net world. My favorite Json library is the Json.Net. Since, I started to code a wrapper about it.

Suppose now you have such an object, that you have Json serialized:

var obj = new
{
    Name = "mouk",
    FavoriteNames = new[] { "mouk", "dermouk", "mouk9000" },
    NestedValues = new { First = 1, Second = 3, Nums = new[] { 1, 2, 3 } },
    NestedArray = new object[]{ 1, 3, new[] { 100, 2, 3 } },
    Age = 25,
    Height = 180
};

var serializedObject = JsonConvert.SerializeObject(obj);

After deserializing it back to a dynamic object you can access as easy as:

dynamic _deserializedObject = JsonDeserilizer.GetObjectFromString(serializedObject);

string name= _deserializedObject.Name;
int age = _deserializedObject.Age;

int nested = _deserializedObject.NestedArray[1];

Source Code

The source code of this wrapper can be downloaded from http://github.com/mouk/JsonToDynamic/tree/master:

2 Responses to “JsonToDynamic: Consuming Json Data as Dynamic Objects in C# 4.0”

  1. RAMI ALISAWI

    Hello,

    Nice topic , I’m wondering if you knew anything on transforming DOM objects to JSON objects?

    Regards,
    -Rami

  2. Moukarram Kabbash

    Do you mean dom objects in the browser?
    In the .Net world, you can serialize almost any object to Json using the described Json.Net library.

Leave a Reply