Friday 6 January 2012

Article on JSON with ASP.NET



I hope this small article related to JESON to help you to built high quality of concepts.  This article is dedicated to the developer who wants to learn JESON by quick start.
What is JSON?
  • JSON stands for JavaScript Object Notation
  • 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.
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 Rules
JSON syntax is a subset of the JavaScript object notation syntax.
  • Data is in name/value pairs
  • Data is separated by comma
  • Curly brackets holds objects
  • Square brackets holds arrays
JSON Name/Value Pairs
JSON data is written as name/value pairs.
A name/value pair consists of a field name (in double quotes), followed by a colon, and followed by a value:
"firstName" : "John"
This is simple to understand, and equals to the JavaScript statement:
firstName = "John"
JSON Values
JSON values can be:
  • A number (integer or floating point)
  • A string (in double quotes)
  • A Boolean (true or false)
  • An array (in square brackets)
  • An object (in curly brackets)
  • null
JSON Objects
JSON objects are written inside curly brackets,
Objects can contain multiple name/values pairs:
{ "firstName":"John" , "lastName":"Doe" }
This is also simple to understand, and equals to the JavaScript statements:
firstName = "John"
lastName = "Doe"

JSON Arrays
JSON arrays are written inside square brackets.
An array can contain multiple objects:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
In the example above, the object "employees" is an array containing three objects. Each object is a record of a person (with a first name and a last name).
JSON Uses JavaScript Syntax
Because JSON uses JavaScript syntax, no extra software is needed to work with JSON within JavaScript.
With JavaScript you can create an array of objects and assign data to it like this:
Example
var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
];

A security feature of ASP.NET web services that are JSON serialized through the ASP.NET AJAX extensions is that they must be requested in a specific way.
The request must be an HTTP POST request
The request’s content-type must be: “application/json; charset=utf-8

When you register and call a web service through ASP.NET AJAX’s ScriptManager, you may safely enjoy blissful ignorance of these requirements. The framework transparently handles everything for you.

How to use Json with jQuery

The solution is a bit less intuitive than using the ScriptManager or what you would normally expect from jQuery. Using jQuery’s getJSON() would make sense, but it unfortunately meets neither of the above security criteria.

The most reliable way that I’ve found is to use jQuery.ajax() as follows:
Ex: 1
<script language="javascript">
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "WebService.asmx/WebMethodName",
        data: "{}",
        dataType: "json"
    });
</script>
 
Ex: 2
<script language="javascript">
    $(document).ready(function() {
        $.ajax({
            type: "POST",
            url: "RSSReader.asmx/GetRSSReader",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                // Hide the fake progress indicator graphic.
                $('#RSSContent').removeClass('loading');

                // Insert the returned HTML into the <div>.
                $('#RSSContent').html(msg.d);
            }
        });
    });
</script>
As you can see, the first parameters set the request type and content-type as required by the ASP.NET AJAX framework.

When making a read-only request, the empty data parameter is the key. For reasons unknown, jQuery does not properly set the specified content-type when there is no data included.

The “{}” data parameter represents an empty JSON object, which you can think of as the JSON equivalent of null. Supplying this parameter will convince jQuery to correctly send the content-type that we’ve supplied, while it will be safely ignored by the web service.
How to call A WebMethod of a Page
Method in Javascript file
$.ajax({
        type: "POST",
        url: "R3frmnSalesOrderPortal.aspx/fnShowBill",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{'strJson':'" + n + "'}",
        success: function(a) {
            //Do the needful
        },
        error: function() {
            alert('Error')
        }
    })
Method in .cs file
[WebMethod]
public static Dictionary<string, object> fnShowBill(string strJson)
{
    #region [ JSON TO OBJECT ]
    string[] LC = strJson.Split(new string[] { "\",\"" }, StringSplitOptions.None);
            string LocationCode = LC[0].Split(new string[] { "\":\"" }, StringSplitOptions.None)[1];
            string Customer = LC[1].Split(new string[] { "\":\"" }, StringSplitOptions.None)[1].Replace("\"}", "");
            #endregion

            //Your DataSet get from Database
            DataSet dt = new DataSet();
           
            #region [ JSON ]
            Dictionary<string, object> _oo = new Dictionary<string, object>();
            _oo.Add("Grid", JsonMethods.ToJson(dt.Tables[0]));
            _oo.Add("OtherInfo", JsonMethods.ToJson(dt.Tables[1]));
            _oo.Add("Default", JsonMethods.ToJson(dt.Tables[2]));
            return _oo;
            #endregion

            return _oo;
        }

Written By: Mr. Palash Paul

No comments:

Post a Comment