1. 语法
JSON(JavaScriptObject Notation)一种简单的数据格式,比xml更轻巧。JSON是JavaScript原生格式,这意味着在JavaScript中处理JSON数据不需要任何特殊的API或工具包。
JSON的规则很简单:对象是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’对”之间使用“,”(逗号)分隔。
规则如下:
1)映射用冒号(“:”)表示。名称:值
2)并列的数据之间用逗号(“,”)分隔。名称1:值1,名称2:值2
3)映射的集合(对象)用大括号(“{}”)表示。{名称1:值1,名称2:值2}
4)并列数据的集合(数组)用方括号(“[]”)表示。
[
{名称1:值,名称2:值2},
{名称1:值,名称2:值2}
]
5 元素值可具有的类型:string,number, object, array, true, false, null
2. 解析JsonJSON只是一种文本字符串。它被存储在responseText属性中
为了读取存储在responseText属性中的JSON数据,需要根据JavaScript的eval语句。函数eval
会把一个字符串当作它的参数。然后这个字符串会被当作JavaScript代码来执行。因为JSON
的字符串就是由 JavaScript代码构成的,所以它本身是可执行的.
例子一: <script language="JavaScript"> var people ={"firstName": "Brett", "lastName":"McLaughlin", email": "brett@newInstance.com" }; alert(people.firstName); alert(people.lastName); alert(people.email); </script>
例子二: <script language="JavaScript"> var people =[ {"firstName": "Brett","email": "brett@newInstance.com" }, {"firstName": "Mary","email": "mary@newInstance.com" } ]; alert(people[0].firstName); alert(people[0].email); alert(people[1].firstName); alert(people[1].email); </script>
例子三: <script language="JavaScript"> var people ={ "programmers": [ { "firstName": "Brett", "email": "brett@newInstance.com" }, { "firstName": "Jason", "email": "jason@servlets.com" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" } ], "authors": [ { "firstName": "Isaac", "genre": "science fiction" }, { "firstName": "Tad", "genre": "fantasy" }, { "firstName": "Frank", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "instrument": "guitar" }, { "firstName": "Sergei", "instrument": "piano" } ]}; window.alert(people.programmers[1].firstName); window.alert(people.musicians[1].instrument); </script>
3. Json的优缺点
优点:
•作为一种数据传输格式,JSON与
XML 很相似,但是它更加灵巧。
•JSON不需要从服务器端发送含有特定内容类型的首部信息。
缺点:
•语法过于严谨
•代码不易读
•eval函数存在风险
4. 示例:
bean对象 province.java
public class Province { private Integer id; private String province; public Province(Integer id,String province) { this.id = id; this.province = province; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } }处理请求的JsonServlet.java,JSONArray 需要导入json的第三方包json-lib-2.3-jdk15.jar,及其依赖包。
public class JsonServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); //利用javabean来模拟数据库 Province p1 = new Province(1, "吉林省"); Province p2 = new Province(2, "辽宁省"); Province p3 = new Province(3, "山东省"); List<Province> list = new ArrayList<Province>(); list.add(p1); list.add(p2); list.add(p3); JSONArray json = JSONArray.fromObject(list); //String json = "[{'province':'吉林省'},{'province':'辽宁省'},{'province':'山东省'}]"; out.println(json.toString()); //响应始终以字符串形式 } }显示页面 json.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>form.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <select id="province" name="province"> <option value="">请选择....</option> </select> <select id="city" name="city"> <option value="">请选择.....</option> </select> </body> <script language="JavaScript"> window.onload = function(){ var xhr = ajaxFunction(); xhr.onreadystatechange = function(){ if(xhr.readyState==4){ if(xhr.status==200){ var data = xhr.responseText; alert(data); /* * 利用eval()函数转换成json数据格式,传入eval()函数的内容还是文本内容 * * 利用eval()函数进行转换json数据格式,需要利用"()"将传入的参数进行包裹 * * 如果不利用"()"进行包裹,传入的内容是"{}",这时eval()函数会将其识别成"空的语句块" * * 如果利用"()"进行包裹,传入的内容是"{}",这时eval()函数会强行将其转换成json格式 * * * 加上"()"一定转换成功 */ var json = eval("("+data+")"); for(var i=0;i<json.length;i++){ var provinceValue = json[i].province; var optionElement = document.createElement("option"); optionElement.setAttribute("value",provinceValue); var provinceText = document.createTextNode(provinceValue); optionElement.appendChild(provinceText); var provinceElement = document.getElementById("province"); provinceElement.appendChild(optionElement); } } } } xhr.open("post","../jsonServlet?timeStamp="+new Date().getTime(),true); xhr.send(null); } function ajaxFunction(){ var xmlHttp; try{ // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e){ try{// Internet Explorer xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){} } } return xmlHttp; } </script> </html>