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="" 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 小记的更多相关文章
- JSON小记
json: { "1" : "2", "1" : "3" } 在json中如果有重复的key,会取最后一个key的值,如 ...
- Newtonsoft.Json小记
/*json相关*/ //http://www.cnblogs.com/hongfei/p/3593936.html string jsonObject = "{\"phone\& ...
- 临时处理小记:把Numpy的narray二进制文件转换成json文件
临时处理一个Numpy的二进制文件,分析知道里面是dict类型,简单小记一下,如果Numpy和Python基础不熟悉可以看我之前写的文章 In [1]: %%time import numpy as ...
- json学习小记
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- JavaScript中字符串转Json方法小记
例如: JSON字符串:var str1 = '{ "name": "cxh", "sex": "man" }'; JS ...
- JavaScript对json操作小记
JSON是一种轻量级的数据交换格式,同时,JSON是 JavaScript 原生格式,因此我们可以直接处理它不需要依赖任何工具包或者插件.因此,好多后台都会选择返回给前端这种非常友好的数据格式. 引子 ...
- (转)JavaScriptSerializer,DataContractJsonSerializer解析JSON字符串功能小记
JsonAbout: using System;using System.Collections.Generic;using System.Linq;using System.Text;using S ...
- Json数组操作小记 及 JSON对象和字符串之间的相互转换
[{"productid":"1","sortindex":"2"},{"productid":&q ...
- 小记SpringMVC与SpringBoot 的controller的返回json数据的不同
近期由于项目的改动变更,在使用springmvc和springboot测试的时候发现一个有趣的现象 1.springmvc的controller使用@ResponseBody返回的仅仅是json格式的 ...
随机推荐
- ng-class用法
在angular中为我们提供了3种方案处理class: 1:scope变量绑定.这种方案不推荐,因为scope里最好处理业务逻辑,不去管渲染的事.2:字符串数组形式.3:对象key/value处理. ...
- SVG 和字符图标
制作网站往往需要使用一些图标来提高用户体验,如果我们的是一些扁平化设计的图标,我们可以选择 SVG 或 图标字体来提高用户体验. 下面对这两种技术进行比较. 开发难度: 现在的在线工具非常强大,比如 ...
- C# Winform中执行post操作并获取返回的XML类型的数据
/// <summary> /// 返回指定日期的订单数据 /// </summary> /// <param name="StartDate"> ...
- MVC 授权过滤器 AuthorizeAttribute
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...
- python 3.5 之 单双三引号
1. 单引号和双引号用法都是一样的,但是如果字符串里有相同的字符时要使用\进行转义 举例:1) print 'hello'2) print "hello"1和2,结果都是hello ...
- Matplotlib不显示图形
安装好了Matplotlib,使用官方一个例子测试运行时,发现使用画图功能时,运行脚本老是显示不出图像,Google了一下,后来发现是matplotlibrc文件没配置好. 参考了官方文档,修改步骤如 ...
- Python第一印象,大法好!
为了用flask开发web应用,这两天就开始看了一点点Python.还没看到用Python写网站后台的那部分,就被其强大的数据处理能力和语法的灵活性吸引.肯定是我少见多怪,不过看到人家灵活使用Pyth ...
- 提升Boolean和out相结合的用户体验
在我们编写代码的过程中经常有这样的需求,比如添加一条数据,我们想要的结果是如果添加成功了就返回true,如果添加失败了就返回false,在返回false的同时携带错误信息,我们通常的做法是定义这样的方 ...
- C# 迪杰斯特拉(Dijkstra)算法
Dijkstra(迪杰斯特拉)算法是典型的最短路径路由算法,用于计算一个节点到其他所有节点的最短路径.主要特点是以起始点为中心向外层层扩展,直到扩展到终点为止. 其基本思想是,设置顶点集合S并不断地作 ...
- error C2065: 'assert' : undeclared identifier
F:\VC6.0 : error C2065: 'assert' : undeclared identifier 导入#include <assert.h>