JSON - Basics

 JQuery     sbo     Updated on Jun 22, 2013     VIKRAM     701   

Introduction


In this article i will explain what JSON is and how we will perform operations on data using JSON. 

JSON: JavaScript Object Notation.

JSON is syntax for storing and exchanging text information, like XML.

JSON is smaller than XML, and faster and easier to parse.

JSON is lightweight text-data interchange format.

JSON is language independent.

JSON is "self-describing" and easy to understand.

JSON uses JavaScript syntax for describing data objects, but JSON is still language and platform independent. JSON parsers and JSON libraries exists for many different programming languages.

Examples:

Step 1:  Open visual studio

File->New->Web site-> select ASP.NET web Application.

After selecting new ASP.NET Application Go to solution explorer.

Right click on project in solution explorer -> Add New Item. You will get Add New Item popup window in that select Web Form - > name it as JSON.aspx - > OK.  New web page will be added to you web application.

Again right click on Project –> Add New Item –> Select Web Service –> name it as WebService.asmx –> OK.  Web Service class will be added to your project.

WebService.asmx:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
    public WebService () {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }
    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }    
}

Note:  Uncomment the following statement to allow this web service from java script. AJAX.

[System.Web.Script.Services.ScriptService] 

 Uncomment the above line. If That Namespace did not exist then add the following line above the class name.

[System.Web.Script.Services.ScriptService]

Here i will give 3 examples

  1. without parameters
  2. with single parameter
  3. multiple parameters

JSON without parameters:


In this example web method do not have parameters. This method called by AJAX and integer will be displayed. Web method attribute will be added at above the method, as like below.

[WebMethod]

WebService class:

[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {    
    public WebService () {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }
    [WebMethod]
    public int DisplayNumber()
    {
        int x = 10;
        return x;
    }
  }

JSON.aspx page:

To run jQuery add below script in header section of the web page.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

 or download Jquery file and add that file to your project.

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Json.aspx.cs" Inherits="Json" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Json</title>
<%-- <script src="Jquery.js" type="text/javascript"></script>--%>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>   
    <script type="text/jscript" >
        function Json() {           
            var str = "sbo";
            $.ajax({
                url: 'WebService.asmx/DisplayNumber',
                data: '{}',
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    alert(data.d);
                },
                error: function (data) {
                    alert("Error");
                }
            }); // end: $.ajax
        }    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="Button1" type="button" onclick="Json()" value="button" />    
    </div>
    </form>
</body>
</html>

 Note: 

Be careful with single quotes ‘ ’  and double quotes “  ”  They must be nested. If you made any mistakes web method will not be called.

In above Code Snippet: 

$.ajax() 

This method can be used to perform an asynchronous HTTP (Ajax) request.

$.ajax() method returns the jqXHR object, which is a superset of the XMLHTTPRequest object.


url

Type: String

A string containing the URL to which the request is sent.

data

Type: PlainObject or String

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.

dataType (default: Intelligent Guess (xml, json, script, or html))

Type: String

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). 

type (default: 'GET')

Type: String

The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')

Type: String

When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.

success 

Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )

A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.

error

Type: FunctionjqXHR jqXHR, String textStatus, String errorThrown )

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are"timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrownreceives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn.Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is anAjax Event.

For more information, see the jQuery API.

Run this example you will get following output:

Out put:

10.

JSON with single parameter:


JSON.aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Json.aspx.cs" Inherits="Json" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script> 
<script type="text/javascript">
     function Json()  {
         var number1 = 11;        
         $.ajax({
             url: "WebService.asmx/AddTwoNumbers",
         data:"{'x': '"+ number1+"'}",
         dataType:"json",
         type:"post",
         contentType:"application/json; charset=utf-8",
         success:function (data) {
             alert(data.d);
         }, 
         error: function (data) {
             alert("Error");
         }
     }); // end: $.ajax
}
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Test" onclick="Json()" />    
    </div>
    </form>
</body>
</html>

Webservice.asmx:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using
    //ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
    public WebService () {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }
    [WebMethod]
    public string AddTwoNumbers(int x)
    {
        int y = 11;
        int sum = x + y;
        return sum.ToString();
    }    
}

Run this example you will get following output:

Out put:

22.

More than one parameter:


JSON.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Json.aspx.cs" Inherits="Json" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script> 
<script type="text/javascript">
     function Json()  {
         var number1 = 11;
         var number2 = 12;
         $.ajax({
             url: "WebService.asmx/AddTwoNumbers",
         data:"{'x': '"+ number1+"', 'y': '"+ number2+"'}",
         dataType:"json",
         type:"post",
         contentType:"application/json; charset=utf-8",
         success:function (data) {
             alert(data.d);
         }, 
         error: function (data) {
             alert("Error");
         }
     }); // end: $.ajax
}
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="Test" onclick="Json()" />    
    </div>
    </form>
</body>
</html>

Webservice.asmx:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using
    //ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
    public WebService () {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }
    [WebMethod]
    public string AddTwoNumbers(int x, int y)
    {
        int sum = x + y;
        return sum.ToString();
    }    
}

Run this example you will get following output:

Out put:

23.

  Related Articles
How to increase JSON response length in ASP.Net
SQL Server: Date Formats
  Recent Articles
How to increase JSON response length in ASP.Net
SQL Server: Date Formats