Introducing JSON
 
Published: 28 Feb 2007
Abstract
In this article Bilal Haidar introduces JavaScript Object Notation (JSON) and provides an AJAX/JSON example to show the power of JSON when used to interchange data between a client browser and a server.
by Bilal Haidar
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 48337/ 69

Overview

You have always used the Asynchronous JavaScript and XML (AJAX) to allow a web application to send asynchronous requests from the client browser to the server to retrieve some data and then let the client browser running your application receive a server response again in an asynchronous fashion. Data interchange usually was done either in the form of simple human readable strings or in an XML format.

In this article I will be introducing you to a new way of data interchange between the client and server. The idea discussed will focus on JavaScript Object Notation (JSON). I will not be discussing what AJAX is and how the AJAX response is processed on the client side especially if the data received from the server is an XML data, since this is out of the topic of this article, however, I will simply show you how to use JSON format to exchange data.

XML vs. JSON

If you are interested in knowing more about the difference between exchanging data in the XML or JSON format, I would recommend checking the online article "Speeding up AJAX with JSON," which explains in details this subject. This article can be reached here. The author shows how much faster it is to use JSON instead of XML since there will be no construction of the XML DOM tree on the client before being able to access the XML data. Data exchanged in JSON will be nothing but a text human readable data, which can be easily parsed and accessed as a normal object. During this article you will be more introduced to JSON objects, arrays, and other data types and you will see how easy and faster it is to work with JSON especially when we are dealing with web applications AJAX enabled.

What is JSON?

JSON, according to the official website for JSON, is a lightweight data interchange format that is a text-based, human readable format that is used to represent objects, arrays, and other data types that is mainly used to exchange such data types over the network.

JSON is mainly used in web applications AJAX enabled. Such applications force their server-side code, which can be PHP, JSP, ASP.NET, etc … to format the data that they must send back to the requesting client application in a JSON format. Many benefits can be gained out of this process, especially performance gain on the client side since there will be no overhead in generating XML DOM tress out of the XML Data and would be better than simple text in a string-format because JSON would represent the data received in an object-fashion! And all that you have to do on the client is just parse that object-string-formatted into a JSON object and access that object as if you are dealing with a C# or JAVA object!

Since I am talking about objects and arrays, it is worth mentioning that JSON is a subset of the object literal notation of JavaScript and is commonly used with that language. Therefore, since JSON depends on objects and such Object Oriented types, it can be easily used with an Object Oriented Language since they all share the same concept of representing data as objects. Let me show you an example of a JSON object before going on to get a small idea on what I have been talking from the beginning of this article.

Listing 1: JSON simple object

{
      "FirstName""Bilal",
      "LastName""Haidar",
      "Age": 26,
      "Experience":
            ["2004""2005", "2006"]
}
JSON Data Types

JSON is mainly based on two structures:

A collection of name/value pairs which can be thought of as an object, structure, hash table, keyed list, and dictionary in most of the Object Oriented Languages.

A list of values which is similar to the array in most Object Oriented Programming Languages.

JSON Object

An object is represented as follows:

Listing 2: JSON Object

{
  // Properties (name/value pairs separated by comma)
}

When you want to construct a JSON object you simply start by opening right opening curly braces then write down your name/value pairs which are thought of as properties in most of OOP languages.

The object can contain simple name/value pairs, an array of values, an array of objects, and simple values.

Once you have finished writing your own properties, you can add left opening curly braces as if you are closing the object. For those of you who have an experience with C# or JAVA, in those two languages we use the left and right opening curly braces to specify the beginning and ending of an object.

To access a property within your JSON object in JavaScript, you simply write the following:

Listing 3: JSON Object Access

var fname = jsonObject.FirstName

To be able to access a JSON object this way as shown in Listing 3 above, you will have to first parse the string JSON object generated by a server-side language into a JSON object. You can simply use the eval function in JavaScript; however, this function has many security concerns because it can execute any JavaScript statement. A better and clearer way of parsing your string JSON objects to real JSON objects is to use a library that is distributed for free from www.json.org. I will look at this library later on in this article.

JSON Array

A JSON array is a simple array structure that I am sure you have extensively used in your applications while developing either windows or web applications.

In JSON an array can hold simple values or objects. An example of a JSON array is as follows:

Listing 4: JSON Simple Array

"simpleArray": ["value 1""value 2""value 3"]

As you can see, I have constructed a simple array of strings named simplearray. You can even construct an array of integers, floats, double, and even Boolean values. The reason behind naming the array is to be able access its elements. This will be clearer in the next listing where I show you how to access a complex array of objects.

You can also have a more complicated array where you might embed an array of objects.

Listing 5: JSON Complex

"arrayOfObjects":
[
      {
            "name1": "value1",
            "name2": "value2"
      },
      {
            "name3": "value3",
            "name4": "value4"
      }
]

As shown in the above listing, each element is simply a JSON object which is normally allowed in JSON. To access the first property of the second object in the above array, you might write something similar to this code:

Listing 6: JSON Complex Array Access

var name1 = arrayOfObjects[1].name1

Again, if you are going to use the above code you will have to parse the JSON string array into a real JSON array. More on this comes in the next sections of this article.

JSON Property

As mentioned above, JSON is based upon the object and array data structures. Within these data structures you would definitely use properties and values.

A value can be a string, number, object, array, true, false, or null values.

A property is nothing but a value with a name. You can think of each name/value pair as a property.

To have an extensive explanation on the JSON data types please refer to the official JSON website which can be reached at the following URL.

How to generate JSON on the server side

Generating a JSON string object on the server side can be easily done by using a StringBuilder object and appending the objects’ properties into the instance of the StringBuilder. For instance, you convert a C# object into string JSON string object as follows:

Listing 7

public class Person
{
  #region Member fields
  int id =  - 1;
  string name = "";
  #endregion
  #region Properties
  public int ID
  {
    get
    {
      return this.id;
    }
    set
    {
      this.id = value;
    }
  }
  public string Name
  {
    get
    {
      return this.name;
    }
    set
    {
      this.name = value;
    }
  }
  #endregion
 
  #region Constructors
  public Person(): this- 1, ""){}
 
  public Person(int id, string name)
  {
    this.id = id;
    this.name = name;
  }
  #endregion
}
 
// Create a new instance of Person object
Person p = new Person(5, "Bilal Haidar");
// Construct the JSON string object
StringBuilder sb = new StringBuilder();
sb.Append("{");
sb.AppendFormat("\"{0}\": \"{1}\"", p.ID, p.Name);
sb.Append("}");
Response.Write(sb.ToString());

You can see how easy it is to convert your business objects to JSON string objects. You just need to follow the JSON format and you are there!

If you had more complicated objects they might include arrays of objects or simple values. It is not wise to do the conversion yourself in a manual way. Therefore, I will guide you to a great JSON DLL that is called Jason.NET.

An example of how you can utilize the Jason.NET to get a JSON string object is shown in the listing below.

Listing 8

// create a new instance of the Person object
Person p = new Person(5, "Bilal Haidar");
// Convert the C# object into a JSON string object.
string jsonStringObj = JavaScriptConvert.SerializeObject(p);        
// Show the output which shall be something as:
// {"ID":5,"Name":"Bilal Haidar"} 
Response.Write(jsonStringObj);

You can see and feel how easy it is to use the JavaScriptConvert object to get your JSON string objects from the C# objects.

I will not go into details on how to use the Json.NET DLL. You can visit its site to get more tutorials on how to use this helpful DLL when generating JSON data.

How to consume JSON on the client side

You have already seen how the server can generate a response in a JSON string object format. Now it is time to know how to consume the JSON string object on the client side that is how to parse the JSON string object into a real JSON object to be accessed as a normal object you would access in an Object Oriented Programming Language.

I will demonstrate to you an ajaxified example that will send an asynchronous request to the server and then processes the response from the server, assuming that the server will respond by formatting the data in a JSON fashion.

Listing 9

function ReadyStateChangeHandler()
{
  if (xmlHttpRequest.readyState == 4)
// Completed {
    if (xmlHttpRequest.status == 200)
// Response OK {
// Process data
  var jsonStringObj = xmlHttpRequest.responseText;
 
// Parse the JSON string object to a real JSON object
  var jsonObj = jsonStringObj.parseJSON();
 
// display some data
  alert("Person ID: " + jsonObj.ID.toJSONString());
}
 
else
{
  alert("Error: HTTP " + xmlHttpRequest.status + " " +
    xmlHttpRequest.statusText);
}
}
}

The above JavaScript function is usually used to fire when a response is ready from the server. Assume that xmlHttpRequest is a valid instance of the XMLHttpRequest object that has been used to send an asynchronous request to the server, the code first checks if the readystate of the xmlHttpRequest object is 4; a value of 4 means that the request has completed.

Once we are sure the request has completed, we check if the response status from the server is OK. OK means that there was no problem in processing the request and a valid response has been generated by the server. The status of the response has the value of 200 and the description of that status is OK.

If the above two steps were completed successfully, then the code can safely process the response from the server. Assuming the response from the server is formatted in a JSON string object, the code first grasps the response text by using the XMLHttpRequest property called responseText. Once the text is available, the code parses the response text using the parseJSON() function. This function will convert any well-formatted JSON string object into a JSON object.

Once we have a valid JSON object, we access the object properties the same way we access any C# or VB.NET object, by simply specifying the object name, a “.” and the name of the property.

Yahoo!! That is it!! The code alerts the ID of the Person object that was generated on the server in both Listings 7 and 8.

Wait a moment, did you ask yourself where did the parseJSON() and toJSONString() methods come from? Well, those are two major functions among other useful functions that have been prepared by the JSON team. The JSON team prepared a JavaScript utility file named json.js that you need to include into your pages if you are going to use any of those methods. It is recommended to use the methods since they can make your life easier when it comes to processing JSON string objects, arrays and other JSON data types on the client side.

To download the JavaScript utility file, follow this link: http://www.json.org/js.html. On this page you can find an extensive examination of all the available methods ready for you to use out of that great and helpful utility file.

Sample Demo

In this last section of this article, I am going to provide a sample demo. We will go through the code step-by-step and show you all the needed information to enable you to develop such AJAX/JSON enabled ASP.NET web applications.

Figure 1: JSON Demo Web Application

 

 

To start with, let me explain the main idea of the application. As you can see from the form above, it asks the users to select an employee name from the DropDownList. Once an employee is selected using AJAX/JSON, the details of the selected employee will be shown below the DropDownList.

Listing 10 show the code of the above ASP.NET web form.

Listing 10

<div id="page">
        <div id="header">
            <h1>Populating Data with JSON</h1>
        </div>
        <div id="content">
            Select an employee to check his/her record:<br />
            <asp:DropDownList ID="ddlEmployees" runat="server" onchange="GetEmployeeDetails()">
                <asp:ListItem Value="-1" Text="Select Employee"></asp:ListItem>
                <asp:ListItem Value="1" Text="Bilal"></asp:ListItem>
                <asp:ListItem Value="2" Text="Wessam"></asp:ListItem>
                <asp:ListItem Value="3" Text="Sami"></asp:ListItem>
                <asp:ListItem Value="4" Text="Haissam"></asp:ListItem>
            </asp:DropDownList>
            <br /><br />
            <div id="statusDisplay">
                <div id="innerStatusDisplay"></div>
            </div>
            <br /><br />
            <div id="employeeDetails" style="visibility:hidden">
                <table>
                    <tr style="font-weight: bold">
                        <td>First Name</td><td>Last Name</td><td>Years of Experience</td>
                    </tr>
                    <tr>
                        <td class="datacell"><span id="empFname"></span></td>
                        <td class="datacell"><span id="empLname"></span></td>
                        <td class="datacell"><span id="empExperience"></span></td>
                    </tr>
                </table>
            </div>
        </div>
</div>

An onchange function has been added to the DropDownList so that, when the user selects an item from the DropDownList, a JavaScript function will be fired! The JavaScript method to fire named GetEmployeeDetails will start an AJAX request to the server by requesting an ASP.NET web form and supplying the employee ID to whom the details should be displayed.

Listing 11: GetEmployeeDetails function

function GetEmployeeDetails() {    
    postRequest = new HttpRequest();
    postRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    postRequest.failureCallback = requestFailed;
    
    setStatusText("");
    ResetEmployeeDetails();
 
    // Get Employee Selected
    var n = document.forms[0].elements["ddlEmployees"].selectedIndex;
    var empID = document.forms[0].elements["ddlEmployees"].options[n].value;
    
    // Validate the employee ID
    if (empID == -1) {
        setStatusText("Please select a valid employee.");
        return;
    }
 
    var empID = encodeURI(empID);    
    postRequest.url = "GetEmployeeDetails.aspx";
    postRequest.successCallback = responseOK;
    postRequest.post("EmpID=" + empID);
}

The function starts by creating a new instance of the XmlHttpRequest object using a wrapper class called HttpRequest. Then it defines the content type of the request and the failure callback method in case a problem happened while sending the request or receiving a response from the server.

The HttpRequest is a wrapper class created by Mike Hall. Mike has a very educative article on AJAX and I recommend every one of you to check it out and learn from it. It is an AJAX reference if you are planning to introduce AJAX to your web applications. The article can be found here. In last page of this article Mike presents the HttpRequest object which is nothing but a wrapper over the XMLHttpRequest object in either IE7 and FireFox or the different Microsoft ActiveX XmlHttpRequest objects.

The code then gets the employee that was selected from the DropDownList. The employee ID is then encoded and this step is done intentionally because the function is using POST to request another ASP.NET web form to process the request.

Finally, the URL to be requested is assigned to the URL property of the instance of the HttpRequest object and a success callback method is specified, which is the method to fire when the AAJX request is completed and that the response is OK. The last line of the method posts the asynchronous request to the server, requesting the GetEmployeeDetails ASP.NET web form.

Listing 12: GetEmployeeDetails Server side code

protected void Page_Load(object sender, EventArgs e)
{
// Validate the Form object
  if (Request.Form["EmpID"] != null)
  {
    if (!string.IsNullOrEmpty(Request.Form["EmpID"].ToString()))
    {
// Request is OK
      this.requestOK = true;
 
// Get the value of the EmployeeID
      Employee employee = null;
      int empID = Convert.ToInt32(Request.Form["EmpID"].ToString());
 
// Prepare object
      switch (empID)
      {
        case 1:
// Employee Bilal was selected
          employee = new Employee("Bilal", "Haidar", 1, new string[]
          {
            "2005""2006"
          }
          );
          break;
        case 2:
// Employee Wessam was selected
          employee = new Employee("Wessam""Zeidan", 2, new string[]
          {
            "2004""2005", "2006"
          }
          );
          break;
        case 3:
// Employee Sami was selected
          employee = new Employee("Sami""Souki", 3, new string[]
          {
            "2003""2004"
          }
          );
          break;
        case 4:
// Employee Haissam was selected
          employee = new Employee("Haissam""Abdul Malak", 4, new string[]
          {
            "2005""2006"
          }
          );
          break;
        default:
// Wrong Employee Selected
          this.requestOK = false;
          break;
      }
 
      Response.Clear();
      Response.ContentType = "application/json";
      if (this.requestOK)
      {
// Prepare JSON response
        string output = Newtonsoft.Json.JavaScriptConvert.SerializeObject
          (employee);
        Response.Write(output);
      }
      Response.End();
    }
  }
}

The page load of GetEmployeeDetails page first retrieves the employee ID that was posted to it through the AJAX request. This is just a dummy code that will use a C# switch statement to check the employee ID and accordingly a new Employee object is constructed.

Once the employee object is created, the code clears the current response and sets the content type of the response to application/json, which is the right content type when you are sending JSON data to the client.

After that, the employee object is serialized into a JSON string object. Finally, the JSON string object is written back to the client.

Assuming the request/response is done safely (most of the times), the requestOK function will fire on the client. This is the method that was set to the success callback method of the HttpRequest instance.

Listing 13: Success callback function

function responseOK(httpRequest)
{
// Assume no match was found.
  var statusText = "Employee not found!"
 
// Fill in the FirstName, LastName, and years of experience, if available.
  try
  {
// Show the employee etails
    var empDetails = document.getElementById("employeeDetails");
    if (empDetails != null)
      empDetails.style.visibility = "";
 
    var jsonObj = postRequest.responseText.parseJSON();
 
// Set the FirstName
    var fname = document.getElementById("empFname");
    if (fname != null)
      fname.innerHTML = jsonObj.FName.toJSONString();
 
// Set the LastName
    var lname = document.getElementById("empLname");
    if (lname != null)
      lname.innerHTML = jsonObj.LName.toJSONString();
 
    var exp = document.getElementById("empEmployment");
    var splitExp = "";
    for (i = 0; i < jsonObj.YearsOfEmployment.length; i++)
    {
      splitExp = splitExp + jsonObj.YearsOfEmployment[i].toJSONString();
 
      if (i != (jsonObj.YearsOfEmployment.length - 1))
        splitExp = splitExp + ",";
    }
    if (exp != null)
      exp.innerHTML = splitExp;
 
// Update status
    statusText = "Employee Details Found";
  }
  catch (ex){}
 
  setStatusText(statusText);
}

The above function receives the response from the server; it parses the JSON string object into a JSON object using the JSON utility file methods. On thing to mention, you should always check if the response text is null or not before doing any parsing!

Finally, the web form is populated with the details of the employee who was selected from the DropDownList.

There are still some functions left that I did not mention in this article that are part of the demo application. Go over them and if you have any question do not hesitate to contact me and ask me about them.

The following is a snapshot of the page displaying the details of an employee that was selected from the DropDownList:

Figure 2: Demo in action

Downloads

Conclusion

In this article I introduced to you JSON. First, I started with a small introduction to JSON and the difference between JSON and XML. I explained in details what JSON is, discussing the JSON data types, showing how to generate JSON formatted data on the server, how to consume JSON on the client, and finally, a sample demo that combined most of the features you would need when using JSON as the main format of exchanging data between the client and server in an asynchronous way.

Make sure you visit all of the links I have mentioned throughout the article because they are essential for you to get a better understanding of AJAX and JSON.

Last but not least, I would like to send a special thanks to Anand Narayanaswamy, Chief technical editor, ASPAlliance.com and Chrisitian Wenz, author of Programming ATLAS, that Anand referred me to, who helped me solve a problem related to IE7. According to Christian, IE7 does not recycle the existing instance of the XMLHttpRequest object and, therefore, the instance should be reinitialized at every new request.

Hope you enjoyed this article!!

Happy AJAXing!!



User Comments

Title: www   
Name: ww
Date: 2012-12-17 2:41:58 AM
Comment:
www
Title: Argument for Gun Control   
Name: Rick
Date: 2012-12-14 10:19:16 PM
Comment:
Time to take the guns away from the crazies
Title: demo   
Name: vishal
Date: 2012-11-30 7:20:06 AM
Comment:
i am new user....
Title: jason verification   
Name: madhan
Date: 2012-09-13 3:14:23 AM
Comment:
I need to check the jason
Title: fsgfds   
Name: sdfg
Date: 2012-08-15 3:06:30 PM
Comment:
fsdg
Title: dsavsd   
Name: vsdv
Date: 2012-07-10 7:14:56 AM
Comment:
lknvlksndv
Title: m,.,   
Name: ,m.,m.
Date: 2012-06-13 12:30:17 AM
Comment:
,m.,m.
Title: Re: Thanks   
Name: Bilal Haidar
Date: 2012-06-12 9:03:50 AM
Comment:
Most welcome Salman :)
Title: Thanks   
Name: Salman ansari
Date: 2012-06-12 8:59:06 AM
Comment:
Thankyou very much......very useful to me on learning stage of JSON
Title: answer to the query from DHEERAJ   
Name: isha
Date: 2011-05-06 2:05:06 AM
Comment:
cut and paste the 2 lines of code ie.
var postRequest = new HttpRequest();
postRequest.failureCallback = requestFailed; inside the function getemployeedetails on the default.js page in the beginning. Apllication runs fine then. thank you
Title: answer to the query from DHEERAJ   
Name: isha
Date: 2011-05-06 2:03:11 AM
Comment:
the query that dheeraj has asked, i faced the same. it is not the issue of IE7. if u check the Default.js page, there u will find 2 lines of code ie.
var postRequest = new HttpRequest();
postRequest.failureCallback = requestFailed;
written above the function getEmployeedetails().
please cut and paste these 2 lines inside this function in the beginning. the application runs fine then. thank you for this amazing application for beginners in JSON/JQUERY
Title: Best Tutorial   
Name: Yogesh Nandre
Date: 2011-01-20 2:35:00 AM
Comment:
Best due to very easy to learn for new one...
Title: Thank You   
Name: Suresh
Date: 2010-12-06 6:26:19 AM
Comment:
Very nice stuff
Title: Json   
Name: Wilmer Ferreira
Date: 2010-09-06 4:16:52 PM
Comment:
In Visual Studio 2010 exits the System.Runtime.Serialization.Json namespace
Title: JSON   
Name: Reshma
Date: 2010-09-06 3:52:38 AM
Comment:
This article gives me very useful and functionality information about json..
Title: JSON   
Name: Vikas
Date: 2010-05-19 12:22:22 AM
Comment:
This article provides me with the great help on what i needed the most
Title: JSON   
Name: Leela
Date: 2010-03-16 12:47:50 AM
Comment:
This article is very useful.
I am a beginner in .NET and i find many useful things ..)
Thankyou
Title: QUERY   
Name: DHIRAJ
Date: 2009-11-30 1:24:26 AM
Comment:
THERE IS SOME ERROR IN THIS ARTICLE. IF WE SELECT ANY NAME FROM DROPDOWNLIST IT DISPLAYS THE RECORD BUT IF WE SELECT ANOTHER NAME FROM DROPDOWNLIST IT DOES NOT DISPLAYS ANY RECORD.

Plz let me know on my email id:
dhiraj.pandey@nagsoft.com,dhirajkumarpandey@ymail.com
Waiting for ur reply on urgent basis....
Title: Re: IE7 issue   
Name: Martin
Date: 2008-04-04 2:10:49 AM
Comment:
Ok, but what can I do to make it work in IE7 ? I tryed to set postRequest = null; in the GetEmployeeDetails() method but then it turns back with an error ?
Title: Re:   
Name: Bilal Haidar [MVP]
Date: 2008-04-04 2:04:17 AM
Comment:
This is not a problem in the code! I once asked about that and they said it is an IE issue!! Didn't check later what they have done to solve it!

Thanks
Title: IE7 issue   
Name: Martin
Date: 2008-04-04 1:42:19 AM
Comment:
Hi,

I just downloaded the demo app and tested it in IE7 and when i select an "employee" from the dropdown list it shows up as expected, but when I try to choose another one from the dropdown nothing happens, is there an bug in the code ?
Title: Re:   
Name: Bilal Haidar [MVP]
Date: 2007-05-19 2:41:45 AM
Comment:
Yes it is :)

Regards
Title: Where is Jason?   
Name: AbsCoder
Date: 2007-05-18 6:16:26 PM
Comment:
Thanks for the article; good stuff. In the article you make mention twice of "great JSON DLL that is called Jason.NET". Perhaps, I'm dense, but I can't seem to locate said DLL. Do you mean Newtonsoft's Json.NET library? Again, thanks for your contribution to the community!






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-19 7:51:34 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search