小試json
JSON (JavaScript Object Notation)一種簡單的數(shù)據(jù)格式,比xml更輕巧。 JSON 是 JavaScript 原生格式,這意味著在 JavaScript 中處理 JSON 數(shù)據(jù)不需要任何特殊的 API 或工具包。
JSON的規(guī)則很簡單: 對象是一個無序的“‘名稱/值’對”集合。一個對象以“{”(左括號)開始,“}”(右括號)結(jié)束。每個“名稱”后跟一個“:”(冒號);“‘名稱/值’ 對”之間使用“,”(逗號)分隔。
還有一些其它的規(guī)則,如數(shù)組等,具體請看.
http://www.json.org/json-zh.html
需導入的包:
Json包: json-lib.jar開發(fā)包使用
依賴包:
commons-beanutils.jar;
commons-httpclient.jar;
commons-lang.jar;
ezmorph.jar;
morph-1.0.1.jar;
一、首先,來看一個簡單的json數(shù)據(jù)例子
代碼如下:
1 <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
3 <html>
4 <head>
5 <title>My JSP 'index.jsp' starting page</title>
6 <script type="text/javascript">
7 function showJSON(){
8 var user =
9 {
10 "username":"shenang",
11 "age":20,
12 "info": { "tel": "520", "cellphone": "520520"},
13 "address":
14 [
15 {"city":"beijing","postcode":"222333"},
16 {"city":"newyork","postcode":"555666"}
17 ]
18 }
19
20 //alert("name:"+user.username);
21 // alert("age:"+user.age);
22 //alert("tel:"+user.info.tel);
23 //alert("cell:"+user.info.cellphone);
24 //alert("add1:"+user.address[0].city);
25 //alert("add2:"+user.address[0].postcode);
26 alert("name:"+user.username+"\r\r"+"age:" + user.age);
27
28 }
29 </script>
30 </head>
31 <body>
32 <input type="button" onclick="showJSON()" value="使用這個script"/>
33 </body>
34 </html>
35
也可對對象中的值進行修改,如下:
User.username=”json”;
Alert(“username:”+json);
二、一個更深入的例子(對上面的例子進行改進)
如果我們的數(shù)據(jù)更加復雜,那么得將幾個規(guī)則綜合起來用,將數(shù)組和對象有機的結(jié)合,達到需求。
修改后的代碼:
1 <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
3 <html>
4 <head>
5 <title>My JSP 'MyJsp.jsp' starting page</title>
6 <script type="text/javascript">
7 function showJSON(){
8 var user = [
9 {"username":"json","age":20,"info":{"tel":"520","cellphone":"520520"}, "add":"beijin"},
10 {"username":"shenang","age":21, "info":{"tel":"521","cellphone":"521521"}, "add":"shanghui"},
11 {"username":"you","age":22, "info":{"tel":"522","cellphone":"522522"}, "add":"chongqing"}
12 ];
13 alert(user[0].info.tel);
14 alert(user[2].username)
15 }
16 </script>
17 </head>
18 <body>
19 <input type="button" onclick="showJSON()" value="使用這個script"/>
20 </body>
21 </html>
22
除了使用"."引用屬性外,我們還可以使用下面語句:
Alert(user[0][“info”][“tel”])或者alert(user[0].into[“tel”])
總結(jié):
· 現(xiàn)在讀者應該對JSON的使用有點認識了,歸納為以下幾點:
· 對象是屬性、值對的集合。一個對象的開始于“{”,結(jié)束于“}”。每一個屬性名和值間用“:”提示,屬性間用“,”分隔。
· 數(shù)組是有順序的值的集合。一個數(shù)組開始于"[",結(jié)束于"]",值之間用","分隔。
· 值可以是引號里的字符串、數(shù)字、true、false、null,也可以是對象或數(shù)組。這些結(jié)構都能嵌套。
· 字符串和數(shù)字的定義和C或Java基本一致。
同時可以參考:
http://www.cnblogs.com/Truly/archive/2006/12/31/608896.html
http://www.javaeye.com/topic/71343
http://p-x1984.javaeye.com/blog/314168
http://www.json.org/json-zh.html
posted on 2009-04-23 13:50
重慶理工小子 閱讀(1596)
評論(1) 編輯 收藏 所屬分類:
ajax編程