1.简介
JSON是JavaScript表示法:JavaScriptObject Notation。
JSON是存储和交换文本信息的语法,类似XML。
JSON比XML更小、更快、更易解析。
JSON独立于语言。
2.使用
转换为JavaScript对象
JSON 文本格式在语法上与创建 JavaScript 对象的代码相同,无需解析器,JavaScript程序能够使用内建的eval() 函数,用 JSON 数据来生成原生的 JavaScript 对象。
3.Demo
Json1.html
<script type="text/javascript"> //存储对象 var person = {name:"zhangsan",age:25} alert(person.name);</script>
Json2.html
<script type="text/javascript"> //存储数组 var person = [{name:"zhangsan1",age:11}, {name:"zhangsan2",age:22}, {name:"zhangsan3",age:33}] alert(person[2].name);</script>
Json3.html
<script type="text/javascript"> //存储数组,用别名 var person = {"params":[{name:"zhangsan1",age:11}, {name:"zhangsan2",age:22}, {name:"zhangsan3",age:33}] } alert(person.params[1].name);</script>
Json4.html
<script type="text/javascript"> //存储数组,用别名数组 var person = {"params1":[{name:"zhangsan1",age:11}, {name:"zhangsan2",age:22}, {name:"zhangsan3",age:33}], "params2":[{name:"zhangsan1",age:11}, {name:"zhangsan2",age:22}, {name:"zhangsan3",age:33}], "params3":[{name:"zhangsan1",age:11}, {name:"zhangsan2",age:22}, {name:"zhangsan3",age:33}] } alert(person.params3[2].name);</script>
Json5.htm
<body> <h2>通过 JSON 字符串来创建对象</h3> <p> First Name: <span id="fname"></span><br /> Last Name: <span id="lname"></span><br /> </p> <script type="text/javascript"> var txt = '{"employees":[' + '{"firstName":"Bill","lastName":"Gates" },' + '{"firstName":"George","lastName":"Bush" },' + '{"firstName":"Thomas","lastName":"Carter" }]}'; var obj = eval ("(" + txt + ")"); document.getElementById("fname").innerHTML=obj.employees[1].firstName document.getElementById("lname").innerHTML=obj.employees[1].lastName </script></body>
4.JSON文件
JSON 文件的文件类型是 ".json"
JSON 文本的 MIME 类型是"application/json"
5.JSON解析器
提示:eval() 函数可编译并执行任何 JavaScript 代码。这隐藏了一个潜在的安全问题。
使用 JSON 解析器将 JSON 转换为 JavaScript 对象是更安全的做法。JSON 解析器只能识别 JSON 文本,而不会编译脚本。
在浏览器中,这提供了原生的 JSON 支持,而且 JSON 解析器的速度更快。
较新的浏览器和最新的 ECMAScript(JavaScript) 标准中均包含了原生的对 JSON 的支持。
Web 浏览器支持 | Web 软件支持 |
·Firefox (Mozilla) 3.5 ·Internet Explorer 8 ·Chrome ·Opera 10 ·Safari 4 | ·jQuery ·Yahoo UI ·Prototype ·Dojo ·ECMAScript 1.5 |
Json6.html
<body> <h2>通过 JSON 字符串来创建对象</h3> <p> First Name: <span id="fname"></span><br /> Last Name: <span id="lname"></span><br /> </p> <script type="text/javascript"> var txt = '{"employees":[' + '{"firstName":"Bill","lastName":"Gates" },' + '{"firstName":"George","lastName":"Bush" },' + '{"firstName":"Thomas","lastName":"Carter" }]}'; obj = JSON.parse(txt); document.getElementById("fname").innerHTML=obj.employees[1].firstName document.getElementById("lname").innerHTML=obj.employees[1].lastName </script></body>
*如果出现“JSON未定义”,引用附件json.js可解决。
6.Jquery+Servlet+Json(检测用户名是否可用的一个实例)
Login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <script type="text/javascript" src="jquery-1.6.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#test").click(function(){ //alert($("#userName").val()); //向userNameTestAction发送Ajax请求,以id为user的表单里各表单控件作为请求参数 $.get("userNameTestAction",{uuu:$("#userName").val()}, //指定回调函数 function (data){ $("#userInfo").html(data); }, //指定服务器响应为html "html" ); }); }); </script> </head> <body> <form action="loginAction" method="post"> <input type="text" name="userName" id= "userName"><span id="userInfo" style="color: red;"></span><br/> <input type="button" id="test" value="验证用户名是否可用"> </form> <input type="button" id="showUser" value="显示用户信息"><br/> <div id="show"></div> AJAX.... </body></html>
Web.xml
<servlet> <servlet-name>userTest</servlet-name> <servlet-class>com.zpl.servlet.userNameTestAction</servlet-class></servlet><servlet-mapping> <servlet-name>userTest</servlet-name> <url-pattern>/userNameTestAction</url-pattern></servlet-mapping>
userNameTestAction.java
public class userNameTestAction extends HttpServlet{ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter("uuu"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); if("zhangsan".equals(userName)){ System.out.println("用户名已存在!"); out.print("用户名已存在!"); }else{ System.out.println("用户名可用!"); out.print("用户名可用!"); } } }
7.Jquery+Servlet+Json实例
Login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <script type="text/javascript" src="jquery-1.6.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#test").click(function(){ //alert($("#userName").val()); //向userNameTestAction发送Ajax请求,以id为user的表单里各表单控件作为请求参数 $.get("userNameTestAction",{uuu:$("#userName").val()}, //指定回调函数 function (data){ $("#userInfo").html(data); }, //指定服务器响应为html "html" ); }); $("#showUser").click(function(){ //向userNameTestAction发送Ajax请求,以id为user的表单里各表单控件作为请求参数 $.get("userNameTestAction",{uuu:$("#userName").val()}, //指定回调函数 function (data){ alert(data.name); //var dataObj = eval("("+data+")");//为什么不用转换啊? //alert(dataObj.name); $("#userInfo").html(data.name); }, //指定服务器响应为json "json" ); }); }); </script> </head> <body> <form action="loginAction" method="post"> <input type="text" name="userName" id= "userName"><span id="userInfo" style="color: red;"></span><br/> <input type="button" id="test" value="验证用户名是否可用"> </form> <input type="button" id="showUser" value="显示用户信息"><br/> <div id="show"></div> AJAX.... </body></html>
userNameTestAction.java
public class userNameTestAction extends HttpServlet{ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); JSONObject jsonObject = null; Person p1 = new Person(1,"zhangsan"); jsonObject = JSONObject.fromObject(p1); String json = jsonObject.toString(); System.out.println(json); out.print(json); //String str = "{‘name’:‘zhangsan’}";//为什么单引号不可以呢?不科学啊 //String str = "{\"name\":\"sb\"}"; //out.print(str); //System.out.println(str); } }
Person.java
public class Person { private int id; private String name; public Person(){ } public Person(int id, String name) { super(); this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
Web.xml
<servlet> <servlet-name>userTest</servlet-name> <servlet-class>com.zpl.servlet.userNameTestAction</servlet-class></servlet><servlet-mapping> <servlet-name>userTest</servlet-name> <url-pattern>/userNameTestAction</url-pattern></servlet-mapping>