JSON 小记

JSON是在web应用中频繁使用的一种数据结构,在使用过程中经常出现格式错误等等问题,如果能清晰的了解JSON的构成,那将会避免这些错误

英文好的可以查看原文:

地址:http://www.codeproject.com/Articles/773359/Introduction-to-JSON-Using-JSON-in-ASP-NET-Web-App

 

介绍JSON,在ASP.NET Web应用中使用JSON,使用JSON与与数据库进行交互

介绍

在文章中,我将介绍JSON,例如什么是JSON,JSON的用途,为什么是JSON等等,还常见一个简单的示例。在实例中,我将展示怎么在.NET的web应用中使用JSON和如何使用JSON和数据库进行数据交互。在实例中,我通过调用web方法使用json从数据库取的数据,而没有使用服务器端的数据往返(使用AJAX做数据交互,没有使用一般的后端代码进行数据交互)。

背景

JSON 是JavaScript Object Notation的简写,是 Douglas Crockford发明的。实际上,JSON 是XML的一个轻量级的替代品,语言和平台无关的脚本,你可以在www.w3schools.com网站上看到一个简短的介绍。

JSON 是一个通用的,语言独立的数据存储格式。实际上,它类似XML,XML使用标签,而JSON是基于JavaScript对象字符标记的。现在很多编程语言对JSON都是支持的,包括C#, ASP.NET, Java, Perl, PHP, Python, and Ruby. 更多的JSON信息可以在www.JSON.org . 去查看

What is JSON? 【JSON是什么】?
  • JSON是JavaScript中的标准的对象表示法
  • JSON是轻量级的文本-数据交换格式
  • JSON是信息存储和文本信息交换的语法,类似XML
  • JSON比XML更小,更见快速和易于解析
  • JSON是语言独立的 .
  • JSON使用JavaScript语法去描述数据对象,但是JSON依然是语言和平台无关的
  • JSON解析器和JSON库存在于多个不同的语言平台
  • JSON文件后缀名是.json
  • JSON的互联网媒体类型 是application/js.
Uses of JSON 【JSON的使用】
  • JSON格式用来在网络上序列化和传递结构化数据
  • 主要应用在服务器与客户端之间传输数据
  • Web Services 和APIs 使用JSON格式去提供公用数据
  • 它可以用在现在的编程语言上
JSON with JavaScript 【JSON和JavaScript】

JSON是JavaScript中的对象文本标记的一个子集【1】。由于JSON是一个JavaScript的一个子集,JSON在JavaScript中提供了简单的方式来创建和存贮结构数据。

JSON的文本句法与JavaScript创建对象方式是完全一致的。因此,JavaScript程序可以使用内建的eval() 函数处理JSON 数据到JavaScript对象。

JSON数据可以使用AJAX进行传输

【1】原文:JSON is a subset of the object literal notation of JavaScript.  粗体部分字面意思 JavaScript对象字符标记 翻译起来有些别扭。自己理解下应该就是说JavaScript中的表示对象的语法。

Why JSON?  【为什么选择JSON】

对于AjAX应用程序来说,JSON 比XML更快更容易:

使用XML

  • 取的一个XML文档
  • 使用XML DOM来循环XML文档
  • 提取值存储到变量

使用JSON

  • 取的一个JSON字串
  • eval()解析字串
JSON语法

JSON语法是JavaScript对象表示法的一个子集:

  • 数据以键值对方式存储 例如:"name":"liyang"
  • 数据以逗号分隔 例如:"name":"liyang","age":50
  • objects对象用花括号包住 例如:{"name":"liyang","age":50}
  • arrays数组用方括号包住 例如:[{"name":"liyang","age":50},{"name":"lilei","age":24}]

Let’s have a look at the syntax:

让我们看一下语法

<script>
    var data={ "Name" : "Arv" };
    alert(data.Name);
</script> 

 首先,我创建了一个变量来保存数据,然后使用JSON来定义 一个对象,只有一个名称为:Name值为Arv的项

现在我添加一些值:

<script>
   var data={ "Name":"Arv", "Designation":"Software Engineer", "ExperienceInYears":4
  };
</script>
alert('Name : ' + data.Name + 'Designation : ' + data.Designation + 'Total Experience : ' + data.ExperienceInYears);

在数组中使用JSON存储数据

要创建一个JSON数组,将多个objects包含在方括号中

Example:

var description= [{"Name":"Arv", "Designation":"Software Engineer", "ExperienceInYears":4},
                    {"Name":"Rsh", "Designation":"Tester", "ExperienceInYears":2}];

如果要访问信息,我们需要在数组的某个索引下使用相应键名来取的我们想要的数据

例如:

document.write(description[0].Name); // Output: Arv
document.write(description[0].ExperienceInYears); // Output: 4
document.write(description[1].Name); // Output: Rsh 


 

在ASP.NET web引用中使用JSON

在我们的引用中使用JSON,我们需要编写我们的JavaScript方法,在head标签中调用。 或者像下面这样编写:

<script type = "text/javascript">
//write  JSON Code
</script>


 

还有和服务器端通讯的JSONRequest。所以我创建了一个名字为JSONDemoApplication的web应用

你可以在附件列表中找到我上传的一个示例应用,在我的实例中,我创建了一个简单的页面 命名为JSONTest.aspx.

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

<!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 Application</title>
</head>
<body style = "font-family:Arial; font-size:10pt">
<form id="form1" runat="server">
<center>
<table>
<tr><td colspan="4" align="center">
Enter your UserName and select Department See SQL script to know default username and department
</td></tr>
<tr>
<td align="right">
    UserName : </td>
    <td align="left">
    <asp:TextBox ID="txtUserName" runat="server" 
        onkeyup = "OnChange(this)" onblur= "ShowAvailability()"></asp:TextBox>
    <span id = "mesg"></span> </td>
    <td align="right">
    Department : </td>
    <td align="left">
        <asp:DropDownList ID="ddlDepartment" runat="server">
        <asp:ListItem Text="HR" Value="1"></asp:ListItem>
        <asp:ListItem Text="Fianace" Value="2"></asp:ListItem>
        <asp:ListItem Text="Admin" Value="3"></asp:ListItem>
        <asp:ListItem Text="IT" Value="4"></asp:ListItem>
        </asp:DropDownList>
    <span id = "msg2"></span> </td>
    </tr>
    </table>
</center>
</form>
</body>
</html> 
JSONRequest

JSONRequest 是一个全局的JavaScript对象,它提供了三个方法: post, get, and cancel.

JSONRequest.post【1】

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.

In the demo application, I am using post method.

JSONRequest.post takes some parameters:

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】这段英文看代码意思大概就是说下AJAX请求的东东,大家了解即可,就不翻译了。(实在是不好翻译)

So I have created a ShowAvailability function and create JSONRequest:

<script type = "text/javascript">
function ShowAvailability() {
    $.ajax({
        type: "POST",//using post method to send data
        url: "CS.aspx/CheckUserName", //path to find web method CheckUserName
        data: '{userName: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',//assign value to username from textbox
        contentType: "application/json; charset=utf-8",
        dataType: "json",//datatype json is compulsory
        success: OnSuccess,
        failure: function(response) {
            alert(response);
        }
    });
}
function OnSuccess(response) {
    var mesg = $("#mesg")[0];

    switch (response.d) {
        case "0":
            mesg.style.color = "red";
            mesg.innerHTML = "Username not exist";
            break;
        case "1":
            mesg.style.color = "green";
            mesg.innerHTML = "Available";
            break;
        case "error":
            mesg.style.color = "red";
            mesg.innerHTML = "Error occurred";
            break;                     
    }
}
function OnChange(txt) {
   $("#mesg")[0].innerHTML = "";
}
</script>  

把代码放在head标签中间:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="JSONTest.aspx.cs" Inherits="_JSONTest" %>
<!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="scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script type = "text/javascript">
function ShowAvailability() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/CheckUserName",
        data: '{userName: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response);
        }
    });
}
function OnSuccess(response) {
    var mesg = $("#mesg")[0];
    switch (response.d) {
        case "0":
            mesg.style.color = "red";
            mesg.innerHTML = "Username not exist";
            break;
        case "1":
            mesg.style.color = "green";
            mesg.innerHTML = "Available";
            break;
        case "error":
            mesg.style.color = "red";
            mesg.innerHTML = "Error occurred";
            break;                     
    }
}
function OnChange(txt) {
   $("#mesg")[0].innerHTML = "";
}
</script> 
</head>
<body style = "font-family:Arial; font-size:10pt">
<form id="form1" runat="server">
<center>
<table>
<tr><td colspan="4" align="center">
Enter your UserName and select Department See SQL script to know default username and department
</td></tr>
<tr>
<td align="right">UserName : </td>
    <td align="left"><asp:TextBox ID="txtUserName" runat="server" 
        onkeyup = "OnChange(this)" onblur= "ShowAvailability()">
        </asp:TextBox><span id = "mesg"></span> </td>
    <td align="right">Department : </td>
    <td align="left">
        <asp:DropDownList ID="ddlDepartment" runat="server">
        <asp:ListItem Text="HR" Value="1"></asp:ListItem>
        <asp:ListItem Text="Fianace" Value="2"></asp:ListItem>
        <asp:ListItem Text="Admin" Value="3"></asp:ListItem>
        <asp:ListItem Text="IT" Value="4"></asp:ListItem>
        </asp:DropDownList> <span id = "msg2"></span> </td>
    </tr>
    </table>
</center>
</form>
</body>
</html>

现在我们创建一个web方法,来响应我们在前台【JSONTest.aspx】中写的,名称为CheckUserName 的方法,并给它分配一个参数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class _JSONTest : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    [System.Web.Services.WebMethod]
    public static string CheckUserName(string userName)//parameter send from JSON call
    {
        string returnValue = string.Empty;
        try
        {
            string consString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
            SqlConnection conn = new SqlConnection(consString);
            SqlCommand cmd = new SqlCommand("Sp_CheckAvailability", conn);//SP to check username available in database             
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@UserName", userName.Trim());
            conn.Open();
            returnValue = cmd.ExecuteScalar().ToString();
            conn.Close();  
        }
        catch(SqlException ex)
        {
            returnValue = "error" + ex.ToString();
        }
        return returnValue; 
    }
}

我创建了一个表插入了一些数据:

CREATE DATABASE MyJSONDB ----create database
GO
USE MyJSONDB
GO
CREATE TABLE tblLogin  ---create table to check data
(
 EmpUserName NVARCHAR(100),
 EmpDepartment NVARCHAR(100)
)
GO
----Insert dummy data
INSERT INTO tblLogin VALUES('hruser','1')
INSERT INTO tblLogin VALUES('Fianaceuser','2')
INSERT INTO tblLogin VALUES('adminuser','3')
INSERT INTO tblLogin VALUES('ituser','dd','4')
INSERT INTO tblLogin VALUES('productionuser','5')
INSERT INTO tblLogin VALUES('testinguser','6')
GO

然后创建了一个存储过程来检查数据库是否已经存在记录:

CREATE PROCEDURE Sp_CheckAvailability ( @UserName NVARCHAR(100)='')
AS
BEGIN
SELECT COUNT(*) FROM tblLogin WHERE EmpUserName=@UserName
END

Points of Interest

可以看到,在AJAX环境下,我们调用web服务,我们期望获得某种格式的一些数据。好,假如我们在AJAX请求返回XML格式数据,我们需要把XML数据传递给一个XML解析器来处理,然后才能在JavaScript中使用和操作数据。如果我们接受JSON的数据,我们不需要任何事而把结果赋值给一个JavaScript变量,因为JSON已经是JavaScript,我们可以像平常一样直接操作数据。

History

  • 18th May, 2014: Initial version
  • 23 May, 2014 :attchaed demo application to download

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

原文地址:https://www.cnblogs.com/buyixiaohan/p/3753206.html