August 12, 2013

JSON (JavaScript Object Notation)

JSON is a syntax for storing and exchanging data.
JSON is an easier to use alternative to XML.
  • JSON is lightweight data interchange format
  • JSON is language independent because JSON uses JavaScript syntax, but the JSON format is text only, just like XML. Text can be read and used as a data format by any programming language.
  • JSON is "self-describing" and easy to understand
JSON Example
{  :[ ]}
A collection of name/value pairs.
XML

<?xml version="1.0" encoding="UTF-8" ?>
                <name>John</name>
                <age>30</age>
                <cars>Ford</cars>
                <cars>BMW</cars>
                <cars>Fiat</cars>

<?xml version="1.0" encoding="UTF-8" ?>
                <cars>Ford</cars>
                <cars>BMW</cars>
                <cars>Fiat</cars>
               
JSON Array
{
    "name":"John",
    "age":30,
    "cars":[ "Ford", "BMW", "Fiat" ]
}


{"cars":[ "Ford", "BMW", "Fiat" ]}

<?xml version="1.0" encoding="UTF-8" ?>
                <employees>
                                <firstName>John</firstName>
                                <lastName>Doe</lastName>
                </employees>
                <employees>
                                <firstName>Anna</firstName>
                                <lastName>Smith</lastName>
                </employees>


<?xml version="1.0" encoding="UTF-8" ?>
                <type>Fiat</type>
                <model>500</model>
                <color>white</color>
JSON Object

{"employees":[
    {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}
]}






{type:"Fiat", model:"500", color:"white"}

JavaScript Arrays
var cars = ["Ford", "BMW", "Fiat"];

 JavaScript Object

var car = {type:"Fiat", model:"500", color:"white"};


JSON is an easier to use alternative to XML.Similarity, instead of using a parser (like XML does), a JavaScript program can use standard

JavaScript functions to convert JSON data into native JavaScript objects.

<script>
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}'
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>

For AJAX applications, JSON is faster and easier than XML:


<head runat="server">
    <title></title>

    <script src="jquery-1.7.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        function ShowCurrentTime() {
            $.ajax({
                type: "POST",
                url: "Default3.aspx/GetCurrentTime",
                data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function(response) {
                    alert(response.d);
                }
            });
        }
        function OnSuccess(response) {
            alert(response.d);
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        Your Name :
        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
        <input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
    </div>
    </form>
</body>

codebehind

[System.Web.Services.WebMethod]
    public static string GetCurrentTime(string name)
    {
        return "Hello " + name + Environment.NewLine + "The Current Time is: "
            + DateTime.Now.ToString();
    }

-------------------------------------------------------------------------------------------------------
Insert Data using JSON, ASP.NET Web services and jQuery
[WebMethod]
public string ReceiveUpdatesWebservice(string name,string email, string phone, string address) {
using (SqlConnection conn=new SqlConnection(conStr))
{
// Creating insert statement
string sql = string.Format(@"INSERT INTO [SampleTestDB].[dbo].[SampleInfoTable]
([Name]
,[Email]
,[Phone]
,[Address])
VALUES
('{0}'
,'{1}'
,'{2}'
,'{3}')",name,email,phone,address);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
conn.Open();
rowsInserted=cmd.ExecuteNonQuery();
conn.Close();
cmd = null;
}

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function CallService() {
// Creating variables to hold data from textboxes
var name = $('#_txtname').val();
var email = $('#_email').val();
var phone = $('#_phone').val();
var addr = $('#_addr').val();

$.ajax({
type: "POST",
url: "MultipleUpdateWebService.asmx/ReceiveUpdatesWebservice",
data: "{ 'name': '" + name + "','email': '" + email + "', 'phone': '" + phone + "','address':'" + addr + "'}",
contentType: "application/json",
async: false,
success: function(data) {
$('#message').text(data.d);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Name: <asp:TextBox ID="_txtname" runat="server"></asp:TextBox><br />
Email: <asp:TextBox ID="_email" runat="server"></asp:TextBox><br />
Phone: <asp:TextBox ID="_phone" runat="server"></asp:TextBox><br />
Address: <asp:TextBox ID="_addr" runat="server"></asp:TextBox><br />
<input id="_btnSubmit" type="button" value="Submit" onclick="CallService();" />
<span id="message">

</span>

</div>
</form>

No comments: