Published: 04 Jun 2008
By:
Download Sample Code
Thiru Thangarathinam explains how to use JSON as the preferred data format for invoking Web Services from the client side.
Contents [hide] |
---|
Almost any application that you write will involve exchanging data from a client application to the server. This process involves selecting a data format and exchange protocol that will be required to enable this communication. When it comes to selecting these data formats, you have a variety of open standards that you can consider and the ideal choice depends on the requirements of the application.
For example, if you use SOAP based Web services, you format the data in an XML payload that is wrapped within a SOAP envelope. Although XML works well for many application scenarios, its inherent chatty nature makes it less than ideal for certain scenarios. For example, in an AJAX style Web application, you make asynchronous lightweight out-of-band calls to the server side to get the required data without even refreshing the browser. In this scenario, you need a lightweight, open, text-based platform independent data exchange format for transferring data back and forth between the client and server. That’s exactly what the JSON (Java Script Object Notation) standard provides.
This article will discuss the use of JSON in ASP.NET Web applications. In addition, you will also see how to use JSON as a data format for exchanging data from a WCF service to an AJAX based ASP.NET Web application.
To follow along with the examples throughout this article series, you need the following installed on your system:
JSON has simple types and two structures which are very similar to the universally used data structures such as dictionary objects, hash values, key/value pairs, lists, sequences, record sets, arrays and so on. The basic data types supported by JSON are as follows:
true
and false.
null
Let us consider the key characteristics of JSON in the next few sections.
A JSON object is an unordered set of key/value pairs, with keys separated by values using a colon (:). The members inside the object are separated by a comma (,).
Here is a variable that represents a JSON object with three members. A JSON object is always enclosed between curly brackets and the members inside the object are separated by a comma.
As you can see, the first member has the name ProductID
with the value of 1
.
Once you convert the string into a JSON representation, you can access any member value using the dot notation as shown below:
The above code results in the ProductID
value of 1
being displayed through the message box.
Unlike JSON objects, JSON arrays are enclosed between square braces [
]. The JSON array is an ordered sequence of values separated by a comma (,). The values can be any of the primitive types as well as the JSON objects. In addition, you can also embed a JSON array inside another JSON array. Consider the following JSON array that has four string variables:
You will be able to access the above zero based array item through the array index.
The above code displays the values of all the elements inside the array.
To start with, create a new Website named JSONExample using Visual Studio 2008. Once the Web site is created, add a new Web service by selecting the "AJAX-enabled WCF Service" template and name the Web service as ProductService as shown below:
After the project is created, select View->Solution Explorer from the menu so that you can examine the files within the project. The ProductService.cs file located inside the App_Code folder is the class that actually implements the Web service methods. The next section discusses the code of this class in depth.
Open up the ProductService.cs file and add a method named GetProductDetailsByProductID
that retrieves the product details based on the supplied product id. Inside this method, add code to retrieve the product data from the database, convert that into a JSON string format, and finally return it back to the caller. Here is the required code to accomplish this:
The ProductService class is decorated with the AspNetCompatibilityRequirements
mode attribute that indicates that the WCF service should run in ASP.NET compatibility mode. Without this attribute, you will not be able to access the service from ASP.NET. This attribute is automatically generated when you add the "AJAX-enabled WCF Service."
In the GetProductDetailsByProductID
method, you first establish connection to the database and execute the SQL statement that provides the product details as the result. After retrieving the data from the database, you populate the Product object with the values obtained from the SqlDataReader object.
The Product class is simply a placeholder object that contains properties such as ProductID
, Name
, and ProductNumber
that act as the container. The DataContract
and DataMember
attributes allow you to specify that the class and the members of the class are serializable.
Now that you have the data in the Product object, the next step is to convert that into a JSON string representation. For that, you first create an instance of MemoryStream object and supply that as an argument to the constructor of the DataContractJsonSerializer object. The DataContractJsonSerializer class is a new class introduced with .NET Framework 3.5. As the name suggests, this class serializes an object to the JSON data and deserializes the JSON data back to an object.
Once you have the DataContractJsonSerializer object created, you then invoke its WriteObject
method passing in the MemoryStream and the Product object as arguments. After the MemoryStream object is populated, you then convert it into a string format by loading it through the StreamReader object.
Finally, the StreamReader.ReadToEnd
method returns the string representation of the Product object back to the caller.
Before looking at the code required to implement the client, let us understand the steps involved in utilizing the ASP.NET AJAX extensions for invoking the WCF Web service.
<asp:ScriptManager>
element to specify the location of the Web service. Inside this element, you declare the path of the Web service using the Path
attribute of the <asp:ServiceReference>
element. This enables the client side code to dynamically create the proxy for the Web service.The above steps are depicted in the below diagram.
Now that you have seen the steps, let us add a new ASP.NET Web page named ProductServiceClient.aspx to the Web site and modify its code to look as follows:
In the client side, you have a method named OnGetProductDetailsByProductID
, which is invoked when the "Get Product Details" command button is clicked.
From within the OnGetProductDetailsByProductID method, you invoke the Web service method through the proxy class and supply the following arguments:
ProductID
of the Product that is to be retrieved from the database. You retrieve this value from the text box named txtProductID
through the $get
method that is equivalent to document.
getElementById method.Once the Web service method is successfully executed, the proxy automatically calls the OnGetProductDetailsByProductIDComplete
method. In this example, since the value returned from the Web service is a JSON string, you need to convert that into an object so that you can easily work with it from the client side. Since JSON is a subset of JavaScript's object literal notation, you can accomplish this by using the simple eval function.
Note that you need to use parentheses at the time of calling the eval
function because bare objects aren’t considered valid JavaScript. Once you convert the JSON string into a Product object, you can then access its ProductID
, Name
and ProductNumber
properties as if you are accessing a traditional object.
In the above implementation, it is important to notice that eval should only be used to parse JSON if the source of the JSON formatted text is completely trusted. However if you need to process JSON input from less trusted sources, you can use the third-party JSON parsers.
If a valid Product is returned from the function call, you display its contents by setting the values of the corresponding HTML span controls to the returned values. In case an exception occurs during the service execution, the error message returned from the service is displayed through a message box.
When you browse to the ProductServiceClient.aspx file using the browser and search for a product with product id of 1
, the output should be somewhat similar to the following.
When you click on the "Get Product Details" in the above screen, you will notice that the product information is retrieved from the server and displayed in the browser; all without refreshing the page.
Although the examples presented in this installment were simple, they covered some key points. First, you learned the basics of JSON and how to declare JSON objects and arrays. After that you understood the steps involved in creating a WCF service that can be invoked through ASP.NET AJAX extensions. As part of implementing the Web service, you also how to use the new DataContractJsonSerializer class to convert an object representation into a JSON string on the service side. On the client side, you saw how to deserialize the JSON string returned from the service onto an object for further processing.