Serialize & Deserialize JSON Data

Web Services with AJAX
As most of you would already know, AJAX Extension allows you to create proxies to expose web services to be consumed by the Web Browsers. The mechanism for calling these service functions is completely asynchronous and allows you to specify two functions that will be called when the request complete successfully or error out. In addition to the parameter that you can pass to the service methods, you can also pass in a context parameter that will be available to both success and failure functions.

JSON
The default serialization of AJAX web services is JSON. JSON stands for (JavaScript Object Notation) and is a light weight data interchange format. When building an ASP.NET AJAX application with a web service running at its back you can use either JSON or XML as data interchange means between the Web Browser and the Web Server.

The primary advantage of using JSON over XML is that JavaScript has a build in support to handle JSON strings and by just using the eval function one can get an object representation of the serialized data. Also for browsers, parsing JSON string is much more efficient then parsing a XML document. Additionally JSON produces smaller document therefore reducing the request and response pay load which is exactly what you need while implementing AJAX solutions.

DataContractJsonSerliaizer class provides methods for serialization and de-serialization .NET type to JSON. Suppose there is a user profile class as mentioned:

    public class UserProfile
    {
        public string UserName { get; set; }
        public string Email { get; set; }
        public int Age { get; set; }

    }

 

To enable JSON serialization we need to decorate the class with DataContract attribute and member variables that need to be serialized with DataMember attribute. To use both these attribute we need to import System.Runtime.Serialization namespace.

 

    [DataContract]
    public class UserProfile
    {
        [DataMember]
        public string UserName { get; set; }
        [DataMember]
        public string Email { get; set; }
        [DataMember]
        public int Age { get; set; }
    }


Server-Side Serialization
To serialize an object of type UserProfile we need to create a instance of DataContractJsonSerializer which is located in System.Runtime.Serialization.Json namespace, pass in the type that needs to be serialized and use WriteObject mehtod to write serialized string to a stream.

 

   UserProfile Profile = new UserProfile();
   Profile.UserName = "hwaheed";
   Profile.Email = "haroon_6@yahoo.com";
   Profile.Age = 28;
   MemoryStream Stream = new MemoryStream();
   DataContractJsonSerializer JSC;
   JSC = new DataContractJsonSerializer(typeof(UserProfile));
   JSC.WriteObject(Stream, Profile);
   Stream.Flush();
   Stream.Position = 0;
   StreamReader Reader = new StreamReader(Stream);
   string JSONString = Reader.ReadToEnd();

 

The JSON will be like this: 

{"Age":28,"Email":haroon_6@yahoo.com,"UserName":"hwaheed"}

 

Server-Side De-Serialization
The same DataContractJsonSerializer class can be used to de-serialize JSON string. We create it's instance with type that needs to be de-serialized and use ReadObject to read JSON string from stream to initialize object.

 

   UserProfile Profile = new UserProfile();
   MemoryStream Stream;

   Stream = new MemoryStream(Encoding.Unicode.GetBytes(JSONString));
   DataContractJsonSerializer JSC;

   JSC = new DataContractJsonSerializer(typeof(UserProfile));
   Profile = (UserProfile)JSC.ReadObject(Stream);

 

Client-Side De-Serialization
As mentioned earlier JavaScript has built in support for JSON and we can use eval function to get an object representation of the above JSON string.

 

   var Profile = eval("(" + JSONString + ")")

 

This will create a new Profile object with three properties. You can access these properties by the names mentioned in serialized string like:

 

                        Profile.UserName
                        Profile.Email
                        Profile.Age

Client-Side Serialization
To serialize/de-serialze object on client side AJAX 2.0 provides Sys.Serialization.JavaScriptSerializer class. To serialize, use the static serialize method:

 

   var JSONString;

   JSONString = Sys.Serialization.JavaScriptSerializer.serialize(Profile);

 

 

Conclusion

JSON along with it's built in support in .NET and JavaScript has made data interchange between AJAX web service and client considerably light and when carefully implemented can give your application a well deserved performance boost.

 

kick it on DotNetKicks.com

2 Comments

Comments have been disabled for this content.