json教程從入門到使用

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";

}

/**

*?獲得單個值就不用寫了和平常一樣

*/

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末琳钉,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子蛛倦,更是在濱河造成了極大的恐慌歌懒,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,576評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件溯壶,死亡現(xiàn)場離奇詭異及皂,居然都是意外死亡,警方通過查閱死者的電腦和手機且改,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評論 3 399
  • 文/潘曉璐 我一進店門验烧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人又跛,你說我怎么就攤上這事碍拆。” “怎么了慨蓝?”我有些...
    開封第一講書人閱讀 168,017評論 0 360
  • 文/不壞的土叔 我叫張陵感混,是天一觀的道長。 經(jīng)常有香客問我礼烈,道長浩习,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,626評論 1 296
  • 正文 為了忘掉前任济丘,我火速辦了婚禮,結(jié)果婚禮上洽蛀,老公的妹妹穿的比我還像新娘摹迷。我一直安慰自己,他們只是感情好郊供,可當我...
    茶點故事閱讀 68,625評論 6 397
  • 文/花漫 我一把揭開白布峡碉。 她就那樣靜靜地躺著,像睡著了一般驮审。 火紅的嫁衣襯著肌膚如雪鲫寄。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,255評論 1 308
  • 那天疯淫,我揣著相機與錄音地来,去河邊找鬼。 笑死熙掺,一個胖子當著我的面吹牛未斑,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播币绩,決...
    沈念sama閱讀 40,825評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼蜡秽,長吁一口氣:“原來是場噩夢啊……” “哼府阀!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起芽突,我...
    開封第一講書人閱讀 39,729評論 0 276
  • 序言:老撾萬榮一對情侶失蹤试浙,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后寞蚌,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體田巴,經(jīng)...
    沈念sama閱讀 46,271評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,363評論 3 340
  • 正文 我和宋清朗相戀三年睬澡,在試婚紗的時候發(fā)現(xiàn)自己被綠了固额。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,498評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡煞聪,死狀恐怖斗躏,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情昔脯,我是刑警寧澤啄糙,帶...
    沈念sama閱讀 36,183評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站云稚,受9級特大地震影響隧饼,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜静陈,卻給世界環(huán)境...
    茶點故事閱讀 41,867評論 3 333
  • 文/蒙蒙 一燕雁、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧鲸拥,春花似錦拐格、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至撞叨,卻和暖如春金踪,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背牵敷。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評論 1 272
  • 我被黑心中介騙來泰國打工胡岔, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人枷餐。 一個月前我還...
    沈念sama閱讀 48,906評論 3 376
  • 正文 我出身青樓姐军,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子奕锌,可洞房花燭夜當晚...
    茶點故事閱讀 45,507評論 2 359

推薦閱讀更多精彩內(nèi)容

  • 1. Java基礎部分 基礎部分的順序:基本語法著觉,類相關(guān)的語法,內(nèi)部類的語法惊暴,繼承相關(guān)的語法饼丘,異常的語法,線程的語...
    子非魚_t_閱讀 31,662評論 18 399
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理辽话,服務發(fā)現(xiàn)肄鸽,斷路器,智...
    卡卡羅2017閱讀 134,697評論 18 139
  • Spark SQL, DataFrames and Datasets Guide Overview SQL Dat...
    草里有只羊閱讀 18,334評論 0 85
  • 一. Java基礎部分.................................................
    wy_sure閱讀 3,814評論 0 11
  • 阿J是典型的富二代油啤,爹從政娘經(jīng)商典徘,初三開始交女友,班花幸嬉В花白富美逮诲,不亦樂乎,直到大二看見桃子幽告。桃子還蠻普通的梅鹦,不美...
    九大人閱讀 259評論 0 1