Saturday, January 1, 2011

Posted by SAMAJ SHEKHAR

0

Serializing and Deserializing Data from Json to .Net Objects. ( Example Facebook Feeds)


A very very Happy New Year to you all. I thought why not start this year with a nice blog post, so here i am with a post on how to Deserialize data from Json to a .Net Object and back again.Many libraries exist for this Job most notabely the Json.Net and Dynamic Rest library by Nikhil Kothari

But developer community has always asked why microsoft didn't have it in the Frame work. Well now they have one. It comes in frame work now with an added dll of "System.Web.Extentions.dll". That provides us the Class JavascriptSerializer which you can use by including a using statement as follows.

using System.Web.Script.Serialization;

Before going into the code, let us first understand what is JSON, and what is its significance in the modern world of web applications.

What is JSON?

JSON is another format of expressing data, just like XML. But, JSON is very simpler than XML, and tiny than XML. So, it is becoming popular in the web world to choose the JSON notation over XML since JSON notation are usually shorter, and less data to be transmitted if at all they were to be.

A Simple Example

So lets understand this process with an example, since i am currently working on a project which uses facebook to query data, i think this will be helpful to the facebook developer community also. So first you need to define a class that matches the JSON object you are receiving. like a class if a Data in Json looks like below.

{
"obj1":"data",
"obj2":"10004",
"obj3":{
      "subobj1":"data",
      "subobj2":"data"
      }
"obj4":"data"
}

Then the corresponding class for that in .Net will be

public class MyObj1
{
    public string     obj1 { get; set; }
    public int        obj2 { get; set; }
    public MyObj2     obj3 { get; set; }
    public string     obj4 { get; set; }
}

public class MyObj2
{
    public string subobj1 { get; set; }
    public string subobj2 { get; set; }
}

Notice The obj3 in Json is a completely different class as it contains sub fields so a different class fo that in .Net. Also Remember JavascriptSerializer uses reflections to match field or property "names" with that in "Json" so be careful.

Now to deserialize above Json data to the .Net classes juat include the following line.

JavaScriptSerializer sr = new JavaScriptSerializer();
string jsondata = /*your json string here*/;
//Now with this line the Json string will be converted in MyObj1 object type
MyObj1 converted = sr.Deserialize<MyObj1>(jsondata);
Facebook Example (Deserializing Facebook Feeds)

Now the data returned by facebook's Graph API is also in Json and below is an sample data returned by

http://graph.facebook.com/samajshekhar/feed?limit=1

{
   "data": [
      {
         "id": "100000570310973_182862925076050",
         "from": {
            "name": "Samaj Shekhar",
            "id": "100000570310973"
         },
         "message": "#Wow A decade has passed .. #Happy New year to every one....May this new  year be the most luckiest for you and every one.",
         "icon": "http://photos-d.ak.fbcdn.net/photos-ak-snc1/v27562/23/2231777543/app_2_2231777543_9553.gif",
         "actions": [
            {
               "name": "@samajshekhar on Twitter",
               "link": "http://twitter.com/samajshekhar?utm_source=fb&utm_medium=fb&utm_campaign=samajshekhar&utm_content=20985773201301504"
            }
         ],
         "type": "status",
         "application": {
            "name": "Twitter",
            "id": "2231777543"
         },
         "created_time": "2010-12-31T23:32:54+0000",
         "updated_time": "2010-12-31T23:32:54+0000"
      }
   ],
   "paging": {
      "previous": "http://graph.facebook.com/samajshekhar/feed?limit=1&since=2010-12-31T23%3A32%3A54%2B0000",
      "next": "http://graph.facebook.com/samajshekhar/feed?limit=1&until=2010-12-31T23%3A32%3A53%2B0000"
   }
}

Don't get confused its just little more data of different types including arrays. ( To get data from facebook you can use System.Net.HttpWebRequest and System.Net.HttpWebResponse class). So Now the equivalent .Net classes will be as follows.

Note:

I have included only the classes needed for the above feed for a complete class that accommodate all fields returned in feed with and without access token can be found here at

http://thesharepage.codeplex.com/SourceControl/changeset/view/5405#100657

public class FacebookFeedsWithoutToken
{
 public FacebookFeedWithoutToken[] data { get; set; }
 public ReturnedDataPaging paging { get; set; }
}

public class FacebookFeedWithoutToken
{
 public string id { get; set; }
 public NameIdPair from { get; set; }
 public string message { get; set; }
 public Uri icon { get; set; }
 public NameLinkPair[] actions { get; set; }
 public string type { get; set; }
 public NameIdPair application { get; set; }
 public DateTime created_time { get; set; }
 public DateTime updated_time { get; set; }
}

public class NameIdPair
{
 public string name { get; set; }
 public string id { get; set; }
}

public class NameLinkPair
{
 public string name { get; set; }
 public Uri link { get; set; }
}

Now the classes are ready we just need to convert from json string to .Net object types. add the following line similar to above.

JavaScriptSerializer sr = new JavaScriptSerializer();
string jsondata = /*your json string here*/;
FacebookFeedsWithoutToken converted = sr.Deserialize<FacebookFeedsWithoutToken>(jsondata);

Thats all you have to do.

And once again Happy new year.

READ MORE - Serializing and Deserializing Data from Json to .Net Objects. ( Example Facebook Feeds)