json教程從入門到使用
一:入門
簡介:
JSON(JavaScriptObject Notation)、輕量級數(shù)據(jù)交換格式、非常適合于服務器與 JavaScript 的交互瀑梗。
JSON兩種格式:
1收津、對象
對象是一個無序的“‘名稱/值’對”集合。一個對象以“{”(左括號)開始菩颖,“}”(右括號)結(jié)束样漆。每個“名稱”后跟一個“:”(冒號);“‘名稱/值’ 對”之間使用“,”(逗號)分隔晦闰。
2放祟、數(shù)組
數(shù)組是值(value)的有序集合。一個數(shù)組以“[”(左中括號)開始呻右,“]”(右中括號)結(jié)束跪妥。值之間使用“,”(逗號)分隔。
(具體格式可參照www.json.org声滥、這里只做簡略介紹眉撵、下方會貼出具體相關(guān))
javascript中的JSON相關(guān):
一:對象型JSON
二:數(shù)組型JSON
$(document).ready(functionshowStudent(){
varstudent?=
[
{"sno":"001","name":"jack","age":130},
{"sno":"002","name":"tame","age":120},
{"sno":"003","name":"cule","age":110},
];
//以下是兩種獲取值的方法
document.write('sno:'+?student[0].sno?+'????name:'+student[0].name?+'????age?:'+student[0].age?+'
');
document.write('sno:'+?student[0]["sno"]?+'???name:'+?student[0]["name"]?+'????age?:'+?student[0]["age"]+'
');
document.write('sno:'+?student[1]["sno"]?+'???name:'+?student[1]["name"]?+'????age?:'+?student[1]["age"]+'
');
document.write('sno:'+?student[1]["sno"]?+'???name:'+?student[1]["name"]?+'????age?:'+?student[1]["age"]+'
');
document.write('sno:'+?student[2]["sno"]?+'???name:'+?student[2]["name"]?+'????age?:'+?student[2]["age"]+'
');
document.write('sno:'+?student[2]["sno"]?+'???name:'+?student[2]["name"]?+'????age?:'+?student[2]["age"]+'
');
});
三:相互嵌套(僅舉一種、可自己弄著玩試試)
[javascript]view plaincopy
$(document).ready(functionshowStudent(){
varstudent?=
{
"sno":"001",
"name":"jack",
"age":130,
"address":
[
{"pro":"anhui","city":"fuyang"},
{"pro":"jiangsu","city":"nanjing"}
]
}
document.write('sno:'+?student.sno????+'????name:'+?student.name????+'???age?:'+?student.age????+'????pro?:'+?student.address[0].pro?+'????city?:'+?student.address[0].city+'
');
});
補充:至于JSON為什么能這樣取得數(shù)據(jù)的值落塑??It is based on a subset of theJavaScript Programming Language,StandardECMA-262 3rd Edition - December 1999.????? 它是javascript的一個子集纽疟、javascript會對其進行解析(如何實現(xiàn)暫不理會)。
四:json格式的字符串憾赁、和json對象(對于什么時候稱作json對象不做深究)的區(qū)別:
很簡單:json格式的字符串污朽、很明顯就是一個字符串、只具有字符串的特性和功能龙考。只是格式上看起來像json對象而已蟆肆、而不具有json對象所具有的功能(比如上面的例子中拿到student對象的某個屬性的值矾睦、上面是String的話、student.sno能獲得sno的值嗎颓芭?某老師的話:自己動手試試……)顷锰。
$(document).ready(functionshowStudent(){
varstudent?=
{
"sno":"001",
"name":"jack",
"age":130,
"address":
[
{"pro":"anhui","city":"fuyang"},
{"pro":"jiangsu","city":"nanjing"}
]
}
document.write('sno?:'+?student.sno????+'????name:'+?student.name????+'????age?:'+?student.age????+'????pro?:'+?student.address[0].pro?+'????city?:'+?student.address[0].city?+'
');
});
注意:別把
typeof(studentJson)+'
'寫成
typeof(studentJson?+'
')
這樣就成了JSON對象與String拼接了、結(jié)果會變成兩個string…
JSON格式Str與JSON對象之間的轉(zhuǎn)換
一:Object轉(zhuǎn)換成JSONStr
? $(document).ready(functionObject2JSONString(){
varstudent?=newStudent("001","chy");
varstudentJson?=?student.toJSONString();
document.write(typeof(studentJson)?+'
');
document.write(studentJson?+'
');
});
//toJOSNString()?可以把json格式的字符串或者Object轉(zhuǎn)換成json對象
functionStudent(sno,?name){
this.sno?=?sno;
this.name?=?name;
}
二:JSONStr轉(zhuǎn)換成JSON對象
? $(document).ready(functionstr2json?()?{
varstudentStr??='{"sno":"001","name":"jack","age":123}';
//不推薦亡问、存在安全隱患
varstudentJson?=?eval('('+studentStr+')');
//缺陷:不能適用于所有的瀏覽器
varstudentJson2?=?JSON.parse(studentStr);
//需下載jquery.json-2.4.js官紫、未實現(xiàn)
//var?studentJson3?=?jQuery.toJSON(studentStr);
//document.write(typeof(studentJson3)+'
'?);
document.write(typeof(studentStr)?+'
');
document.write(typeof(studentJson)+'
');
document.write(typeof(studentJson2)+'
');
})
三:JSON對象轉(zhuǎn)換成JSONStr
? $(document).ready(functionjson2str?()?{
varstudentJson??=?{"sno":"001","name":"jack","age":123};
//toJSONString()方法需要借助json.js文件(可去官方網(wǎng)站下載)
varstudentStr?=?studentJson.toJSONString();
varstudentStr2?=?JSON.stringify(studentJson);
document.write(studentStr?+'
');
document.write(studentStr2?+'
');
document.write(typeof(studentStr)?+'
');
document.write(typeof(studentJson)+'
');
})
JSON遍歷
四種遍歷方式:
functionfirstMethod(){
varlist1?=?[1,3,4];
document.write(list1[1]+'
');
varlist2?=?[{"name":"leamiko","xing":"lin"}];
document.write(list2[0]["xing"]+'
');
document.write(list2[0].xing+'
');
document.write("==========================================================="+'
');
}
functionsecondMethod(){
varvalue?=
{
"china":
{
"hangzhou":{"item":"1"},
"shanghai":{"item":"2"},
"chengdu":{"item":"3"}
},
"America":
{
"aa":{"item":"1"},
"bb":{"item":"2"}
},
"Spain":
{
"dd":{"item":"1"},
"ee":{"item":"2"},
"ff":{"item":"3"}
}
};
//向里循環(huán)的時候只能用external[internal][deeperinternal]...而不能用external.internal.deeperinternal...原因不知道。州藕。束世。當json類型是{...}時for(var?x?in?value)x指的是每一個值、當json類型是[]時?x指的是數(shù)組下標床玻。根據(jù)情況利用
for(varcountryinvalue){
document.write(country?+':
');
for(varcityinvalue[country]){
document.write('???'+city+':
');
for(variteminvalue[country][city]){
document.write('???'+value[country][city][item]+':
');
}
}
}
document.write("==========================================================="+'
');
}
functionthirdMethod(){
varvalue?=?{
"china":
[
{"name":"hangzhou","item":"1"},
{"name":"shanghai","item":"2"},
{"name":"sichuan","item":"3"}
],
"America":
[
{"name":"aa","item":"12"},
{"name":"bb","item":"2"}
],
"Spain":
[
{"name":"cc","item":"1"},
{"name":"dd","item":"23"},
{"name":"ee","item":"3"}
]
};
for(varcountryinvalue){
document.write(country+'
');
for(varxinvalue[country]){
document.write('cityname:?'+?value[country][x]["name"]?+'??item:?'+?value[country][x]["item"]?+'
');
}
}
document.write("==========================================================="+'
');
}
functionfourthMethod(){
varvalue?=?{
"china":
[
{"name":"hangzhou","item":"1"},
{"name":"shanghai","item":"2"},
{"name":"sichuan","item":"3"}
],
"America":
[
{"name":"aa","item":"12"},
{"name":"bb","item":"2"}
],
"Spain":
[
{"name":"cc","item":"1"},
{"name":"dd","item":"23"},
{"name":"ee","item":"3"}
]
};
for(varcountryinvalue){
document.write(country+'
');
for(vari=0;?i
document.write('cityname:?'+?value[country][i]["name"]?+'??item:?'+?value[country][i]["item"]?+'
');
}
}
document.write("==========================================================="+'
');
}
$(document).ready=firstMethod();
$(document).ready=secondMethod();
$(document).ready=thirdMethod();
$(document).ready=fourthMethod();
JSON在struts2中的使用
說白了毁涉、json在java web項目中的應用本質(zhì)就是客戶端請求到服務端、服務端將數(shù)據(jù)處理成json格式返回給客戶端锈死、客戶端再根據(jù)返回的數(shù)據(jù)進行下一步操作贫堰。。待牵。采用json就
是因為json更容易和快速的被解析其屏、我們又可以根據(jù)自己的需要在后臺設定好數(shù)據(jù)格式、這樣在前臺可以直接拿來用或者加工一下缨该。偎行。。贰拿。
(最好是下個能直接用的項目蛤袒、然后自己動手多試、自己搭膨更、如果jar包沖突妙真、搞了半天沒解決、什么激情也沒有了荚守、還什么都沒有干隐孽、、健蕊、)
只搞一種菱阵、有時間補充:
1、jar包
commons-beanutils-1.7.0.jar
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-lang-2.3.jar
commons-logging-1.0.4.jar
ezmorph-1.0.3.jar
freemarker-2.3.15.jar
json-lib-2.1.jar
ognl-2.7.3.jar
struts2-core-2.1.8.1.jar
struts2-json-plugin-2.1.8.1.jar
xwork-core-2.1.6.jar
2缩功、struts.xml
3晴及、jsp
<%@?pagelanguage="java"pageEncoding="GBK"%>
<%
Stringpath=request.getContextPath();
%>
Struts2+JQuery+JSON
/js/jquery.js">
/js/jsonstyle.js">
用戶ID:
用戶名:
密???碼:
其中的jsonstyle.js代碼:
//初始加載頁面時
$(document).ready(function(){
//為獲取單個值的按鈕注冊鼠標單擊事件
$("#getMessage").click(function(){
$.getJSON("jsontest!returnMessage.action",function(data){
//通過.操作符可以從data.message中獲得Action中message的值
$("#message").html(""+data.message+"");
});
});
//為獲取UserInfo對象按鈕添加鼠標單擊事件
$("#getUserInfo").click(function(){
$.getJSON("jsontest!returnUserInfo.action",function(data){
//清空顯示層中的數(shù)據(jù)
$("#message").html("");
//為顯示層添加獲取到的數(shù)據(jù)
//獲取對象的數(shù)據(jù)用data.userInfo.屬性
$("#message").append("
用戶ID:"+data.userInfo.userId+"
")
.append("
用戶名:"+data.userInfo.userName+"
")
.append("
密碼:"+data.userInfo.password+"
")
});
});
//為獲取List對象按鈕添加鼠標單擊事件
$("#getList").click(function(){
$.getJSON("jsontest!returnList.action",function(data){
//清空顯示層中的數(shù)據(jù)
$("#message").html("");
//使用jQuery中的each(data,function(){});函數(shù)
//從data.userInfosList獲取UserInfo對象放入value之中
$.each(data.userInfosList,function(i,value){
$("#message").append("
第"+(i+1)+"個用戶:
")
.append("
用戶ID:"+value.userId+"
")
.append("
用戶名:"+value.userName+"
")
.append("
密碼:"+value.password+"
");
});
});
});
//為獲取Map對象按鈕添加鼠標單擊事件
$("#getMap").click(function(){
$.getJSON("jsontest!returnMap.action",function(data){
//清空顯示層中的數(shù)據(jù)
$("#message").html("");
//使用jQuery中的each(data,function(){});函數(shù)
//從data.userInfosList獲取UserInfo對象放入value之中
//key值為Map的鍵值
$.each(data.userInfosMap,function(key,value){
$("#message").append("
用戶ID:"+value.userId+"
")
.append("
用戶名:"+value.userName+"
")
.append("
密碼:"+value.password+"
");
});
});
});
//向服務器發(fā)送表達數(shù)據(jù)
$("#regRe").click(function(){
//把表單的數(shù)據(jù)進行序列化
varparams?=?$("form").serialize();
//使用jQuery中的$.ajax({});Ajax方法
$.ajax({
url:"jsontest!gainUserInfo.action",
type:"POST",
data:params,
dataType:"json",
success:function(data){
//清空顯示層中的數(shù)據(jù)
$("#message").html("");
//為顯示層添加獲取到的數(shù)據(jù)
//獲取對象的數(shù)據(jù)用data.userInfo.屬性
$("#message").append("
用戶ID:"+data.userInfo.userId+"
")
.append("
用戶名:"+data.userInfo.userName+"
")
.append("
密碼:"+data.userInfo.password+"
")
}
});
});
});
4、action
packagestruts2jsonjquery.test.action;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importstruts2jsonjquery.test.entity.UserInfo;
importcom.opensymphony.xwork2.ActionSupport;
publicclassJsonJqueryStruts2ActionextendsActionSupport?{
privatestaticfinallongserialVersionUID?=?3518833679938898354L;
privateString?message;//使用json返回單個值
privateUserInfo?userInfo;//使用json返回對象
privateList?userInfosList;//使用josn返回List對象
privateMap?userInfosMap;//使用json返回Map對象
//為上面的的屬性提供get嫡锌,Set方法
publicString?getMessage()?{
returnmessage;
}
publicvoidsetMessage(String?message)?{
this.message?=?message;
}
publicUserInfo?getUserInfo()?{
returnuserInfo;
}
publicvoidsetUserInfo(UserInfo?userInfo)?{
this.userInfo?=?userInfo;
}
publicList?getUserInfosList()?{
returnuserInfosList;
}
publicvoidsetUserInfosList(List?userInfosList)?{
this.userInfosList?=?userInfosList;
}
publicMap?getUserInfosMap()?{
returnuserInfosMap;
}
publicvoidsetUserInfosMap(Map?userInfosMap)?{
this.userInfosMap?=?userInfosMap;
}
/**
*?
*??返回單個值
*?
*?@return
*/
publicString?returnMessage(){
this.message?="成功返回單個值";
return"message";
}
/**
*?
*??返回UserInfo對象
*?
*?@return
*/
publicString?returnUserInfo(){
userInfo?=newUserInfo();
userInfo.setUserId(10000);
userInfo.setUserName("張三");
userInfo.setPassword("000000");
return"userInfo";
}
/**
*?
*??返回List對象
*?
*?@return
*/
publicString?returnList(){
userInfosList?=newArrayList();
UserInfo?u1?=newUserInfo();
u1.setUserId(10000);
u1.setUserName("張三");
u1.setPassword("000000");
UserInfo?u2?=newUserInfo();
u2.setUserId(10001);
u2.setUserName("李四");
u2.setPassword("111111");
UserInfo?u3?=newUserInfo();
u3.setUserId(10002);
u3.setUserName("王五");
u3.setPassword("222222");
UserInfo?u4?=newUserInfo();
u4.setUserId(10003);
u4.setUserName("趙六");
u4.setPassword("333333");
userInfosList.add(u1);
userInfosList.add(u2);
userInfosList.add(u3);
userInfosList.add(u4);
return"list";
}
/**
*?
*??返回Map對象
*?
*?@return
*/
publicString?returnMap(){
userInfosMap?=newHashMap();
UserInfo?u1?=newUserInfo();
u1.setUserId(10000);
u1.setUserName("張三");
u1.setPassword("000000");
UserInfo?u2?=newUserInfo();
u2.setUserId(10001);
u2.setUserName("李四");
u2.setPassword("111111");
UserInfo?u3?=newUserInfo();
u3.setUserId(10002);
u3.setUserName("王五");
u3.setPassword("222222");
UserInfo?u4?=newUserInfo();
u4.setUserId(10003);
u4.setUserName("趙六");
u4.setPassword("333333");
userInfosMap.put(u1.getUserId()+"",?u1);
userInfosMap.put(u2.getUserId()+"",?u2);
userInfosMap.put(u3.getUserId()+"",?u3);
userInfosMap.put(u4.getUserId()+"",?u4);
return"map";
}
/**
*?
*??獲得對象虑稼,也就是通過表達獲得對象(異步的)
*?
*?@return
*/
publicString?gainUserInfo(){
System.out.println("用戶ID:"+userInfo.getUserId());
System.out.println("用戶名:"+userInfo.getUserName());
System.out.println("密碼:"+userInfo.getPassword());
return"userInfo";
}
/**
*?獲得單個值就不用寫了和平常一樣
*/
}