Introduction To JSON

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 accessthe  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 is gives short quik references for JSON and accesing databases using JSON in Asp.net web application with sql server database. JSON full form is JavaScript Object Notation , and it was invented by Douglas Crockford. Actually JSON is 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, 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 :

JSON format is used for serializing & transmitting structured data over network connection. This is primarily used to transmit data between server and web application. 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={ "Name" : "Arv" };  
  3. alert(data.Name);  
  4. </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={ "Name":"Arv""Designation":"Software Engineer""ExperienceInYears":4  
  3. };  
  4. </script>  
  5. alert('Name : ' + data.Name + 'Designation : ' + data.Designation + 'Total Experience : ' + data.ExperienceInYears);  
Storing JSON Data in Arrays :

To crteate JSON Array enclose multiple objects in square brackets

Example-:
  1. var description= [{"Name":"Arv""Designation":"Software Engineer""ExperienceInYears":4},  
  2. {"Name":"Rsh""Designation":"Tester""ExperienceInYears":2}];  
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 frunction 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 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 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.   
  11. public partial class _JSONTest : System.Web.UI.Page   
  12. {  
  13.     protected void Page_Load(object sender, EventArgs e)  
  14.     {  
  15.     }  
  16.     [System.Web.Services.WebMethod]  
  17.     public static string CheckUserName(string userName)  
  18.     {  
  19.         string returnValue = string.Empty;  
  20.         try  
  21.         {  
  22.             string consString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;  
  23.             SqlConnection conn = new SqlConnection(consString);  
  24.             SqlCommand cmd = new SqlCommand("Sp_CheckAvailability", conn);              
  25.             cmd.CommandType = CommandType.StoredProcedure;  
  26.             cmd.Parameters.AddWithValue("@UserName", userName.Trim());  
  27.             conn.Open();  
  28.             returnValue = cmd.ExecuteScalar().ToString();  
  29.             conn.Close();    
  30.         }  
  31.         catch(SqlException ex)  
  32.         {  
  33.             returnValue = "error" + ex.ToString();  
  34.         }  
  35.         return returnValue;   
  36.     }  
  37. }  
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:

Up Next
    Ebook Download
    View all
    Learn
    View all