Wednesday, June 17, 2009

AJAX & JSON Serialization



This article provides an overview of JSON's rules and illustrates how it is used in AJAX-enabled web applications.

Transmitting information over the Internet requires the sender to serialize it into some string-based format prior to sending it, and the receiver to deserialize it back into an object state that it can work with. For instance, if the client wants to send an array of integers to the server it must convert that array from its in-memory representation into a string, so that it can be transmitted across the network. Likewise, upon receiving the request, the receiver must turn that string representation of an array of integers back into an array of integers, so that it can use it programmatically.


XML was designed to serialize complex data into a string-based format, and early AJAX frameworks used XML as the serialization format. However, modern AJAX implementations use an alternate serialization format known as JavaScript Object Notation, or JSON. Like XML, JSON is an open, Text-Based Serialization Format, that is both human-readable and platform independent.


It differs from XML in three important ways:


·         It is much simpler to understand and implement than XML;

·         It is less verbose, resulting in a slimmer payload; and,

·         Most importantly, Data serialized in JSON can automatically be parsed by JavaScript - In other words, working with data formatted in JSON in JavaScript does not require a separate Deserialization library or custom code to parse a message.


This article provides an overview of JSON's rules and illustrates how it is used in AJAX-enabled web applications. We'll also look at using the Microsoft ASP.NET AJAX framework's JavaScriptSerializer class, which facilitates serializing and deserializing JSON-formatted messages on the client in JavaScript or in C# or Visual Basic code on the server. Read on to learn more!


JSON - In AJAX-enabled Web Applications


When using Script Services (Web Services) in an AJAX-enabled ASP.NET application, the ASP.NET AJAX framework automatically handles generating and parsing the JSON messages sent between the client and server.


However there may be times when you want to create or parse JSON messages yourself, either in JavaScript or in server-side code. For example, the AJAX Control Toolkit is an open-source collection of AJAX-enabled Web controls for ASP.NET websites. Many of these controls use script services to communicate with the server. These controls expect script services with a pre-defined method signature; that is, they expect the script service method they are configured to use to accept a specific number of input parameters and return a value of a specific type. In cases where you, the page developer, may need to supply additional information in the script service call, the script service signature will offer an additional string input parameter into which you can pass any input. If you need to pass a single additional input parameter you can do so through this extra parameter. If you need to pass two or more additional input parameters then you'll need to serialize them into a string representation, pass them in this single input parameter, and then deserialize them in the script service.


In such a case, you can serialize the additional input parameters using JSON.


The Microsoft ASP.NET AJAX Framework includes both client- and server-side mechanisms for creating and parsing JSON messages.


·         To create or parse JSON messages in C# or VB code, use the JavaScriptSerializer class, which is found in the System.Web.Script.Serialization namespace.

·         To create or parse JSON messages in JavaScript, use the Sys.Serialization.JavaScriptSerializer class, which is part of the ASP.NET AJAX framework's client-side API.



The download includes two demos that show how to do the serialization: JsonSerializationOnServer.aspx, which serializes the array in C# and Visual Basic code; and JsonSerializationOnClient.aspx, which serializes the array in JavaScript code using the ASP.NET AJAX framework's client-side API. I'll let you explore the download to see exactly how things work, but here's a snippet of how the serialization takes place on the server (it's quite easy):


Below is a simple Server Side JSON example.



List<int> selectedCategories = new List<int>();

// selectedCategories.Add(1)


JavaScriptSerializer json = new JavaScriptSerializer();
string jsonMessage = json.Serialize(arrayOfCategoryIDs);



JavaScriptSerializer json = new JavaScriptSerializer();
List<int> categories = null;

if (jsonMessage != null)

   categories = json.Deserialize<List<int>>(jsonMessage);





JavaScriptSerializer Class


The JavaScriptSerializer class is used internally by the Asynchronous Communication Layer to serialize and deserialize the data that is passed between the browser and the Web server. You cannot access that instance of the serializer. However, this class exposes a public API. Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.




JSON Message Format - Syntax


JSON, or JavaScript Object Notation, is a data-exchange format based on JavaScript's literal object notation.

JSON's syntactic rules are more strict than JavaScript's, but are quite similar and quite simple.

Here's the one-line overview:


“JSON-formatted messages are composed of a single, top-level object or array, which itself can hold objects, arrays, strings, numbers, Boolean values, or the value null. “


An object is an unordered set of name/value pairs and is denoted using a subset of JavaScript's literal object notation, and follows the rules we just discussed in the previous section (namely, that the


  • Name/value pairs are encased in curly braces,
  • The name is in quotes,
  • Name/value pairs are delimited by commas, and
  • The name and value are delimited by a colon.
  • Arrays are an ordered collection of values encased within square brackets and with each name/value pair delimited by a comma.
  • Strings are text encased in quotation marks;
  • Numbers are the digits that make up the number;
  • The two boolean values are the tokens true and false; and
  • The null value is the token null.


XML Format

JSON Format

<Employee EmployeeID="1">


   "EmployeeID": 1,
   "Name": "Scott",
   "Salary": 75000,
   "Certifications": [ "MCSD", "CCNP", "MCP" ]



Reading JSON Message in JS - Syntax



JSON Format



var emp = eval( jsonString );

alert("Employee " + emp.Name + " makes " + emp.Salary + " per year!");





Reference: Link


Thanks & Regards,

Arun Manglick || Senior Tech Lead



No comments:

Post a Comment