Building Interactive User Interfaces with Microsoft ASP.NET AJAX: A Look at JSON SerializationBy Scott Mitchell
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.
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
in C# or Visual Basic code on the server. Read on to learn more!
An Overview of Literal Notation
Programming languages often include some syntax for defining a literal, or fixed value in code. For example, in C# or Visual Basic you can express the literal value of a number by simply typing it; to express the literal value of a string you surround the text by quotation marks. The following code snippet shows assigning the literal value of "Hello, World!" and 3.14159 to string and decimal variables in C# and Visual Basic, respectively.
"Hello, World!" and
3.14159 that appear in the above code are examples of literals.
In the past, C# and Visual Basic had a rather limited set of literals. There were strings, numbers, Boolean values, and arrays, for instance. Over the years, these languages
have been enhanced to include support for additional literals. Visual Basic 9 added support for XML literals and object initializers. C# 3.0 also supports object initializers,
as well as collection initializers. Visual Basic and C#'s object initializers allow objects to be defined literally. The following snippet, taken from
An Extensive Examination of LINQ: Extension Methods, Implicitly Typed Variables, and Object Initializers,
shows C# and VB code that creates a new
Employee object by literally defining the object's properties and values:
The literal syntax differs based on the literal and the programming language, although most languages use the same syntax for primitive literals like numbers, strings, and
Boolean values. As the example above shows, the syntax for C#'s object initializers encompasses the property values within curly braces that appear right after the class name
Employee, in this case). Each class property/value pair appears within the curly braces and the value/pair are delimited by an equals sign. The property/value
pairs are delimited from one another via a comma. In VB, the
With keyword denotes the start of the object initializer. Like with C#, the property/value pairs are
placed within curly braces and are delimited from one another with commas. However, each property name must be prefixed with a period.
Objects can also be defined literally using the following syntax:
from one another by a comma. The main difference is that the property names (
Name, etc.) are encased in quotation marks and the
are optional. However, the JSON standard, as we'll not shortly, requires that the property names of object's be quoted.)
Also note that the object literal notation is not limited to simple types. The
emp object defined above has a property named
that is an array. Likewise, the literal arrays notation can contain complex types; you could literally define an array of objects, where each object was literally defined.
false; and the null value is the token
JSON in AJAX-Enabled Web Applications
JSON is the preferred serialization format for AJAX-enabled web applications for a number of reasons. For starters, it's much simpler than XML. There are built-in data types, no confusing namespaces, strict yet simple rules for formatting, and native object and array support. Granted, this simplicity does not allow for the breadth of features and uses that XML's complexity affords, but this simplicity does make it easier to implement and use JSON.
Second, JSON will always result in a slimmer payload than XML, as it encodes data with fewer characters. A web application that shuttles fewer bytes over the Internet will appear snappier and more interactive than one that uses heavier payloads.
out-of-band calls to the server to get information about employees. The client might send in the querystring the
EmployeeID value, while the server would respond
with a payload that includes the requested employee's information. If that payload was XML-formatted, the response from the server for a particular employee might look like the
and would likely take anywhere from 5-25 lines of code.
If the web server responded with a JSON-formatted payload, things would be much simpler. Instead of the above XML payload, the server could respond with the following JSON message:
eval function like so:
Where jsonString is the contents of the JSON message returned from the server. After executing the above line of code the variable
emp is assigned to the
object denoted by the JSON message! It now has the properties
Certifications at its disposal.
(In actuality, AJAX frameworks do not use the
eval function to parse JSON messages, but instead use their own approach that first verifies that the JSON message
does not include any potentially dangerous script.)
JSON In Action
The previous installment in this article series, Retrieving Server-Side Data Using Web Services, looked at how to create script services using Microsoft's ASP.NET AJAX Framework. Script services are Web Services that are enhanced to allow for data to be serialized via JSON rather than via SOAP and XML. The Retrieving Server-Side Data Using Web Services article included a demo of a script service named
NorthwindServicesthat, among other things, had a method named
AnswerQuickSummaryReportQuerythat would return the number of products in the database that matched a certain criteria, such as, "How many products cost less than $5.00?" or, "How many products cost exactly $15.00?"
NorthwindServices script service was called from an ASP.NET page whenever the user clicked a particular button on the page. Clicking that button executed
proxy class makes an HTTP request to the script service, passing the input parameters as a JSON message and receiving back a JSON message as response. Using
Fiddler or any other HTTP traffic analyzing tool, you can inspect the content sent by the proxy class to the script service and
see the response.
NorthwindServices and asking how many products cost less than $15 sends the following JSON message to the script service:
This is a JSON message. There's a top-level object that contains two properties,
queryCost, with string values of "CostLess" and "15.00".
NorthwindServices script service takes these values, deserializes them and passed them into the
AnswerQuickSummaryReportQuery method. This
method then queries the database to get the number of products that meet this criteria. This count is returned by the
The script service serializes the return value into the following JSON message, which is sent back to the client as the response.
The following diagram illustrates this workflow.
For more information on using Fiddler to examine HTTP traffic be sure to check out Troubleshooting Website Problems by Examining the HTTP Traffic.
Generating and Parsing JSON Messages
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
System.Web.Script.Serialization namespace. To create or parse JSON
the ASP.NET AJAX framework's client-side API.
The demo available for download at the end of this article includes examples of using both the server- and client-side JSON serialization implementations in the ASP.NET AJAX
Framework. Specifically, the demo pages illustrate using the AutoComplete control
from the AJAX Control Toolkit. The AutoComplete control adds auto-complete support to textboxes in a web page, providing a list of possible matches based on the characters the
user has already entered into the textbox. The control calls a script service that you specify, passing it the text the user has entered and expecting back a string array of
possible matches, which is then displays in a list beneath the textbox. This script service may optionally include a string
contextKey input parameter for any
additional information needed.
The demo I created has the user select one or more categories from a series of checkboxes. The AutoComplete then only lists possible product matches based on the selected categories.
For this to work, we need to pass in the set of selected category IDs into the script service. But all we have at our disposal is that single
contextKey input parameter.
The solution is to serialize the array of category IDs into a JSON message and pass that message as the
contextKey input parameter. This involves serializing the
array of category IDs into a JSON message and then deserializing it from a string back into an array of category IDs in the C# or Visual Basic script service code.
The download includes two demos that show how to do the serialization:
JsonSerializationOnServer.aspx, which serializes the array in C# and Visual Basic code;
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):
Simply create an instance of the
Serialize method, passing in the object to serialize. The resulting string
returned by the method is the JSON message corresponding to the passed-in object.
Likewise, deserializing the JSON message into an object is a straightforward task with the
AutoComplete.asmx script service; the code below deserializes the passed-in JSON message into an array of integers (the selected category ID values).