Thursday, September 20, 2012

Convert JSON to .Net Entities – Alternate Way


Often, there are multiple ways to do the same thing in code.

In my previous post, I demonstrated how to convert JSON to .Net entities using the classes in System.Runtime.Serialization and System.Runtime.Serialization.Json namespace.

The alternate is to use classes in Windows.Data.Json namespace.
http://msdn.microsoft.com/en-us/library/windows/apps/windows.data.json.aspx

I came across this style while doing the Contoso Cookbook lab examples, which has the original code.

Below is the code snippet of converting the JSON String to .Net Entitity classes. This example uses the entity classes from previous example. However, it populates each and every property by individually assigning it values. While its more lines of code than the previous example, it can be useful when your .Net Class structure differs from the JSON structure.
Namespaces you need to refer:
using Windows.Data.Json;

Code:
string jsonFriendsString = "{\"data\":[{\"uid\":560275290,\"first_name\":\"Vinay\",\"last_name\":\"Bhatia\",\"pic_square\":\"http://profile.ak.fbcdn.net/hprofile-ak-snc7/371731_560275290_925165134_q.jpg\",\"pic_big\":\"http://profile.ak.fbcdn.net/hprofile-ak-snc7/371731_560275290_925165134_n.jpg\",\"timezone\":null,\"current_location\":{\"city\":\"Singapore\",\"country\":\"Singapore\",\"zip\":\"\",\"id\":101883206519751,\"name\":\"Singapore, Singapore\"}},{\"uid\":702608824,\"first_name\":\"Santosh\",\"last_name\":\"Singh\",\"pic_square\":\"http://profile.ak.fbcdn.net/hprofile-ak-ash4/275768_702608824_1698652029_q.jpg\",\"pic_big\":\"http://profile.ak.fbcdn.net/hprofile-ak-ash4/275768_702608824_1698652029_n.jpg\",\"timezone\":null,\"current_location\":{\"city\":\"Edison\",\"state\":\"New Jersey\",\"country\":\"United States\",\"zip\":\"\",\"id\":109295752421654,\"name\":\"Edison, New Jersey\"}},{\"uid\":100001987004026,\"first_name\":\"Mayur\",\"last_name\":\"Udernani\",\"pic_square\":\"http://profile.ak.fbcdn.net/hprofile-ak-prn1/174061_100001987004026_5522672_q.jpg\",\"pic_big\":\"http://profile.ak.fbcdn.net/hprofile-ak-prn1/161176_100001987004026_3945963_n.jpg\",\"timezone\":null,\"current_location\":{\"city\":\"London\",\"state\":\"England\",\"country\":\"United Kingdom\",\"zip\":\"\",\"id\":106078429431815,\"name\":\"London, United Kingdom\"}}]}";

RootObject fbFriends = ConvertJSONToEntity(jsonFriendsString);
 
//Get Friends List
var friendsList = fbFriends.data;

//Loop Through Friends List
foreach (Datum friend in friendsList)
{
       //Do Something
}
 
Convert JSON to .Net Entities:
private RootObject ConvertJSONToEntity(string JSONString)
{
            //Create .Net Entity Classes to populate
            RootObject fbFriends = new RootObject();
            fbFriends.data = new List<Datum>();

            //Parse the JSON String to an JSON Object
            JsonObject objJSON = JsonObject.Parse(JSONString);

            var objElement = objJSON.ElementAt(0);

            JsonArray array = objElement.Value.GetArray();

            foreach (var item in array)
            {
                Datum friend = new Datum();

                var obj = item.GetObject();

                foreach (var key in obj.Keys)
                {

                    IJsonValue val;
                    if (!obj.TryGetValue(key, out val))
                        continue;

                    switch (key)
                    {
                        case "uid":
                            friend.uid = (long)val.GetNumber();
                            break;

                        case "first_name":
                            friend.first_name = val.GetString();
                            break;

                        case "last_name":
                            friend.last_name = val.GetString();
                            break; 

                        case "pic_square":
                            friend.pic_square = val.GetString();
                            break;

                        case "pic_big":
                            friend.pic_big = val.GetString();
                            break;

                        case "timezone":
                            var objTimeZone = val.ValueType;
                            if (objTimeZone != JsonValueType.Null)
                            {
                                friend.timezone = val.GetObject();
                            }
                            else
                            {
                                friend.timezone = "";
                            }

                            break;

                        case "current_location":
                            JsonObject loc = val.GetObject();
                            CurrentLocation curLoc = new CurrentLocation();

                            curLoc.city = loc.GetNamedString("city");
                            curLoc.country = loc.GetNamedString("country");
                            curLoc.zip = loc.GetNamedString("zip");
                            curLoc.name = loc.GetNamedString("name");
                            curLoc.id = loc.GetNamedNumber("id").ToString();

                            friend.current_location = curLoc;
                            break;
                    }//End Switch

                }//End Inner For Each keys

                //Add Object to List    
                fbFriends.data.Add(friend);

            }//end outer foreach

            //Return List of Objects
            return fbFriends;
        }

1 comment:

Anonymous said...

Thanks for the amazing info. I find these posts have a lot of material. I can't wait to get a chance to impliment all these great posts. Thank you very much.