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.

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;

string jsonFriendsString = "{\"data\":[{\"uid\":560275290,\"first_name\":\"Vinay\",\"last_name\":\"Bhatia\",\"pic_square\":\"\",\"pic_big\":\"\",\"timezone\":null,\"current_location\":{\"city\":\"Singapore\",\"country\":\"Singapore\",\"zip\":\"\",\"id\":101883206519751,\"name\":\"Singapore, Singapore\"}},{\"uid\":702608824,\"first_name\":\"Santosh\",\"last_name\":\"Singh\",\"pic_square\":\"\",\"pic_big\":\"\",\"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\":\"\",\"pic_big\":\"\",\"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 =;

//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();
   = 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))

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

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

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

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

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

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


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

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

                            friend.current_location = curLoc;
                    }//End Switch

                }//End Inner For Each keys

                //Add Object to List    

            }//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.