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="" 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=""></asp:ListItem>
<asp:ListItem Text="Fianace" Value=""></asp:ListItem>
<asp:ListItem Text="Admin" Value=""></asp:ListItem>
<asp:ListItem Text="IT" Value=""></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%>")[].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response);
}
});
}
function OnSuccess(response) {
var mesg = $("#mesg")[];
switch (response.d) {
case "":
mesg.style.color = "red";
mesg.innerHTML = "Username not exist";
break;
case "":
mesg.style.color = "green";
mesg.innerHTML = "Available";
break;
case "error":
mesg.style.color = "red";
mesg.innerHTML = "Error occurred";
break;
}
}
function OnChange(txt) {
$("#mesg")[].innerHTML = "";
}
</script>
</head>
<body style = "font-family:Arial; font-size:10pt">
<form id="form1" runat="server">
<center>
<table>
<tr><td colspan="" 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=""></asp:ListItem>
<asp:ListItem Text="Fianace" Value=""></asp:ListItem>
<asp:ListItem Text="Admin" Value=""></asp:ListItem>
<asp:ListItem Text="IT" Value=""></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','')
INSERT INTO tblLogin VALUES('Fianaceuser','')
INSERT INTO tblLogin VALUES('adminuser','')
INSERT INTO tblLogin VALUES('ituser','dd','')
INSERT INTO tblLogin VALUES('productionuser','')
INSERT INTO tblLogin VALUES('testinguser','')
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)

JSON 小记的更多相关文章

  1. JSON小记

    json: { "1" : "2", "1" : "3" } 在json中如果有重复的key,会取最后一个key的值,如 ...

  2. Newtonsoft.Json小记

    /*json相关*/ //http://www.cnblogs.com/hongfei/p/3593936.html string jsonObject = "{\"phone\& ...

  3. 临时处理小记:把Numpy的narray二进制文件转换成json文件

    临时处理一个Numpy的二进制文件,分析知道里面是dict类型,简单小记一下,如果Numpy和Python基础不熟悉可以看我之前写的文章 In [1]: %%time import numpy as ...

  4. json学习小记

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  5. JavaScript中字符串转Json方法小记

    例如: JSON字符串:var str1 = '{ "name": "cxh", "sex": "man" }'; JS ...

  6. JavaScript对json操作小记

    JSON是一种轻量级的数据交换格式,同时,JSON是 JavaScript 原生格式,因此我们可以直接处理它不需要依赖任何工具包或者插件.因此,好多后台都会选择返回给前端这种非常友好的数据格式. 引子 ...

  7. (转)JavaScriptSerializer,DataContractJsonSerializer解析JSON字符串功能小记

    JsonAbout: using System;using System.Collections.Generic;using System.Linq;using System.Text;using S ...

  8. Json数组操作小记 及 JSON对象和字符串之间的相互转换

    [{"productid":"1","sortindex":"2"},{"productid":&q ...

  9. 小记SpringMVC与SpringBoot 的controller的返回json数据的不同

    近期由于项目的改动变更,在使用springmvc和springboot测试的时候发现一个有趣的现象 1.springmvc的controller使用@ResponseBody返回的仅仅是json格式的 ...

随机推荐

  1. Paxos算法深入分析

    在分布式系统设计领域,Paxos可谓是最重要一致性的算法.Google的大牛们称   All working protocols for asynchronous consensus we have ...

  2. Android多项目依赖在Eclipse中无法关联源代码的问题解决 Ctril 点不进去的解决方法

    1. 使用快捷键:Ctrl+shift+R,在弹出框中输入.classpath  找到被作为library引入的那个.classpath文件. 2.将kind="src" path ...

  3. ASP.NET中分布式事务的使用

    之前发表了一篇事务的存储过程,最近在做项目的时候遇到分布式事务,所有总结一下,跟大家分享和交流一下经验.首先说明为什么要分布式事务呢?先说说我在项目的哪里遇到分布式事务吧,我是在做网站后台开发的时候, ...

  4. MVC不错的学习资料

    MVC不错的学习资料: http://www.cnblogs.com/darrenji/

  5. Oracle数据类型与.NET中的对应关系(转)

    Oracle数据类型与.NET中的对应关系 2011-02-24 10:02:16 标签:C# oracletype Oracle 数据类型 .NET Oracle连接添加的引用不同,会存在数据类型不 ...

  6. java面对对象 关键字this super

    this:this是指向对象本身的一个指针,成员函数内部指向当前类的对象 其实this主要要三种用法: 1.表示对当前对象的引用! 2.表示用类的成员变量,而非函数参数,注意在函数参数和成员变量同名是 ...

  7. intellj idea maven 无效的目标发行版: 1.8

    File ->settings->maven->runner->jre -> jdk1.8

  8. function overloading/ declare function

    Declare a function To declare a function without identifying the argument list, you can do it in thi ...

  9. Matplotlib不显示图形

    安装好了Matplotlib,使用官方一个例子测试运行时,发现使用画图功能时,运行脚本老是显示不出图像,Google了一下,后来发现是matplotlibrc文件没配置好. 参考了官方文档,修改步骤如 ...

  10. C#如何连接MySql数据库

    最近两天在解决C#连接MySql数据库的问题,通过不同的从网上学习,最终找到了解决的办法,现在和大家分享一下. 1.要连接MySql数据库必须首先下载MySql官方的连接.net的文件,文件下载地址为 ...