Introduction To JSON

Introduction

 
In this article, I am going to introduce JSON like what JSON is, what is the use of JSON and will create a sample demo application and in this quick demonstration.  I am going to show you how to use JSON with ASP.NET web applications and how to access the database using JSON. And in this demo I am fetching data from the database without server roundtrip by calling web method using JSON. 
 
This article gives short quick references for JSON and accessing databases using JSON in Asp.net web application with sql server database. JSON's full form is JavaScript Object Notation, and it was invented by Douglas Crockford. Actually JSON is a lightweight script protocol alternative to XML and platform independent script.
 
JSON is a universal, language-independent format for data exchange. XML uses tags and JSON is based on the object notation of JavaScript.
 

What is JSON?

  • JSON stands for JavaScript Object Notation. It's a lightweight text-data interchange format. JSON is the syntax used to store and exchange text information, the same as XML.
     
  • JSON is smaller than XML and it is faster and easier to parse. JSON is language independent and uses JavaScript syntax for describing data objects, but JSON is still language and platform-independent. 
     
  • JSON parsers and JSON libraries exist for many programming languages. The JSON filename extension is .json and JSON Internet Media type is application/json.

Uses of JSON

 
The JSON format is used for serializing & transmitting structured data over a network connection. This is primarily used to transmit data between servers and web applications. Web Services and API.s use JSON format to provide public data. It can be used with modern programming languages.
 

Help with JavaScript?

 
JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript. JSON provides for an easy way to create and store data structures within JavaScript. The JSON text format is syntactically identical to the code for creating JavaScript objects. Because of this similarity, instead of using a parser, a JavaScript program can use the built-in eval() function and execute JSON data to produce native JavaScript objects.
 
JSON data can be transported using AJAX.
 

Why JSON?

 
For AJAX applications, JSON is faster and easier than XML:
 
Using XML
  • Fetch an XML document
  • Use the XML DOM to loop through the document
  • Extract values and store in variables
Using JSON
  • Fetch a JSON string
  • eval() the JSON string
JSON Syntax
 
JSON syntax is a subset of the JavaScript object notation syntax:
  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays
Let’s have a look syntax
  1. < script >  
  2.     var data = {  
  3.         "Name""Arv"  
  4.     };  
  5. alert(data.Name); < /script> 
First, I create a variable to hold data and then use JSON to define my object. Just an item called Name and it’s value Arv.
 
Now I add some more values
  1. < script >  
  2.     var data = {  
  3.         "Name""Arv",  
  4.         "Designation""Software Engineer",  
  5.         "ExperienceInYears": 4  
  6.     }; < /script>    
  7. alert('Name : ' + data.Name + 'Designation : ' + data.Designation + 'Total Experience : ' + data.ExperienceInYears); 

Storing JSON Data in Arrays

 
To create JSON Array enclose multiple objects in square brackets
 
Example
  1. var description = [{  
  2.     "Name""Arv",  
  3.     "Designation""Software Engineer",  
  4.     "ExperienceInYears": 4  
  5. }, {  
  6.     "Name""Rsh",  
  7.     "Designation""Tester",  
  8.     "ExperienceInYears": 2  
  9. }]; 
To access this information, we need to access the array index of the description array we wish to access.
 
For example
  1. document.write(description[0].Name); // Output: Arv    
  2. document.write(description[0].ExperienceInYears); // Output: 4    
  3. document.write(description[1].Name); // Output: Rsh 
To use JSON in our application we need to write javascript function and call it on our head tag or we can write as follows:
  1. < script type = "text/javascript" >  
  2.     //write JSON Code    
  3.     < /script> 
And To communicate with server JSON create JSONRequest. So I am creating a web application as named JSONDemoApplication-:
 
and To communicate with server JSON create JSONRequest :
 
JSONRequest is a global JavaScript object. It provides three methods: post, get, and cancel.
 

JSONRequest.post

 
JSONRequest.post does an HTTP POST of the serialization of a JavaScript object or array, gets the response, and parses the response into a JavaScript value. If the parse is successful, it returns the value to the requesting script. In making the request, no HTTP authentication or cookies are sent. Any cookies returned by the server cause the request to fail. The JSONRequest service can only be used to send and receive JSON-encoded values. JSONRequest cannot be used to retrieve other text formats.
 
Here In the demo application, I am using post method JSONRequest.post takes some parameters to,
 
URL- The URL to POST to. The URL does not need to be related to the page's URL.
 
send-object: The JavaScript object or array to send as the POST data. It will be serialized as a JSON text. Cyclical structures will fail.
 

done function (requestNumber, value, exception)

 
The function to be called when the request is completed. If the request was successful, the function will receive the request number and the returned value. If it is not successful, it will receive the request number and an exception object. The done function will not be called until after the call to JSONRequest returns a serial number.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data.SqlClient;  
  8. using System.Configuration;  
  9. using System.Data;  
  10. public partial class _JSONTest: System.Web.UI.Page {  
  11.     protected void Page_Load(object sender, EventArgs e) {}  
  12.         [System.Web.Services.WebMethod]  
  13.     public static string CheckUserName(string userName) {  
  14.         string returnValue = string.Empty;  
  15.         try {  
  16.             string consString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;  
  17.             SqlConnection conn = new SqlConnection(consString);  
  18.             SqlCommand cmd = new SqlCommand("Sp_CheckAvailability", conn);  
  19.             cmd.CommandType = CommandType.StoredProcedure;  
  20.             cmd.Parameters.AddWithValue("@UserName", userName.Trim());  
  21.             conn.Open();  
  22.             returnValue = cmd.ExecuteScalar().ToString();  
  23.             conn.Close();  
  24.         } catch(SqlException ex) {  
  25.             returnValue = "error" + ex.ToString();  
  26.         }  
  27.         return returnValue;  
  28.     }  
Point of interest
 
You see, in an Ajax environment where we make calls to web services we expect to get some data back in some form. Well, if we receive XML back as a direct result of an Ajax call, we have to send that data through an XML parser before we can even begin to manipulate the data to be useful to JavaScript. If we receive the data in JSON...we do not have to do anything but assign the results to a variable because JSON is already JavaScript. From there, we can manipulate the data as normal.
 
Read more articles on JSON