JSON to C# objects

.NET natively supports JSON through System.Web.Script.Serialization.JavaScriptSerializer.
In shorthand, it goes like this:

using System.Web.Script.Serialization;
var obj = new JavaScriptSerializer().Deserialize({YOUR JSON STRING});//String to Object

This, will de-serialize your JSON string to a generic object, but going from this to get a value well within the structure of a JSON string is quite messy:

This is the code of getting the avatar of a disqus user. Messy, unprofessional, difficult to maintain, difficult to read and much more…

var o = (new JavaScriptSerializer()).Deserialize( json );
foreach (var i in ((object[])o["response"])) {
	var c = (Dictionary)i;
	var avatar = (
						((string)
					((Dictionary)
				((Dictionary)
			((Dictionary)c["author"])
				["avatar"])
					["large"])
						["permalink"])
	 );
}

Fortunately there is a better and easier way!
There is this site http://json2csharp.com/ by Jonathan Keith. It uses JSON C# Class Generator to “convert” your JSON string to a series of generic collections of classes with public properties the named keys of your JSON string.
You then just add these classes to your project and cast your JSON string to “RootObject”. Here is the code oding the same job as above:

var o = (new JavaScriptSerializer()).Deserialize( json );
foreach (var c in o.response) {
    var avatar = c.author.avatar.large.permalink;
}
Advertisements

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