json教程從入門到使用

json教程從入門到使用

一:入門

簡介:

JSON(JavaScriptObject Notation)、輕量級數據交換格式、非常適合于服務器與 JavaScript 的交互。

JSON兩種格式:

1、對象

對象是一個無序的“‘名稱/值’對”集合。一個對象以“{”(左括號)開始,“}”(右括號)結束。每個“名稱”后跟一個“:”(冒號);“‘名稱/值’ 對”之間使用“,”(逗號)分隔。

2、數組

數組是值(value)的有序集合。一個數組以“[”(左中括號)開始,“]”(右中括號)結束。值之間使用“,”(逗號)分隔。

(具體格式可參照www.json.org、這里只做簡略介紹、下方會貼出具體相關)

javascript中的JSON相關:

一:對象型JSON

二:數組型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為什么能這樣取得數據的值??It is based on a subset of theJavaScript Programming Language,StandardECMA-262 3rd Edition - December 1999.????? 它是javascript的一個子集、javascript會對其進行解析(如何實現暫不理會)。

四:json格式的字符串、和json對象(對于什么時候稱作json對象不做深究)的區別:

很簡單: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拼接了、結果會變成兩個string…

JSON格式Str與JSON對象之間的轉換

一:Object轉換成JSONStr

? $(document).ready(functionObject2JSONString(){

varstudent?=newStudent("001","chy");

varstudentJson?=?student.toJSONString();

document.write(typeof(studentJson)?+'
');

document.write(studentJson?+'
');

});

//toJOSNString()?可以把json格式的字符串或者Object轉換成json對象

functionStudent(sno,?name){

this.sno?=?sno;

this.name?=?name;

}

二:JSONStr轉換成JSON對象

? $(document).ready(functionstr2json?()?{

varstudentStr??='{"sno":"001","name":"jack","age":123}';

//不推薦、存在安全隱患

varstudentJson?=?eval('('+studentStr+')');

//缺陷:不能適用于所有的瀏覽器

varstudentJson2?=?JSON.parse(studentStr);

//需下載jquery.json-2.4.js、未實現

//var?studentJson3?=?jQuery.toJSON(studentStr);

//document.write(typeof(studentJson3)+'
'?);

document.write(typeof(studentStr)?+'
');

document.write(typeof(studentJson)+'
');

document.write(typeof(studentJson2)+'
');

})

三:JSON對象轉換成JSONStr

? $(document).ready(functionjson2str?()?{

varstudentJson??=?{"sno":"001","name":"jack","age":123};

//toJSONString()方法需要借助json.js文件(可去官方網站下載)

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

}

};

//向里循環的時候只能用external[internal][deeperinternal]...而不能用external.internal.deeperinternal...原因不知道。。。當json類型是{...}時for(var?x?in?value)x指的是每一個值、當json類型是[]時?x指的是數組下標。根據情況利用

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項目中的應用本質就是客戶端請求到服務端、服務端將數據處理成json格式返回給客戶端、客戶端再根據返回的數據進行下一步操作。。。采用json就

是因為json更容易和快速的被解析、我們又可以根據自己的需要在后臺設定好數據格式、這樣在前臺可以直接拿來用或者加工一下。。。。

(最好是下個能直接用的項目、然后自己動手多試、自己搭、如果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){

//清空顯示層中的數據

$("#message").html("");

//為顯示層添加獲取到的數據

//獲取對象的數據用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){

//清空顯示層中的數據

$("#message").html("");

//使用jQuery中的each(data,function(){});函數

//從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){

//清空顯示層中的數據

$("#message").html("");

//使用jQuery中的each(data,function(){});函數

//從data.userInfosList獲取UserInfo對象放入value之中

//key值為Map的鍵值

$.each(data.userInfosMap,function(key,value){

$("#message").append("

用戶ID:"+value.userId+"

")

.append("

用戶名:"+value.userName+"

")

.append("

密碼:"+value.password+"

");

});

});

});

//向服務器發送表達數據

$("#regRe").click(function(){

//把表單的數據進行序列化

varparams?=?$("form").serialize();

//使用jQuery中的$.ajax({});Ajax方法

$.ajax({

url:"jsontest!gainUserInfo.action",

type:"POST",

data:params,

dataType:"json",

success:function(data){

//清空顯示層中的數據

$("#message").html("");

//為顯示層添加獲取到的數據

//獲取對象的數據用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";

}

/**

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

*/

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,406評論 6 538
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,034評論 3 423
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,413評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,449評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,165評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,559評論 1 325
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,606評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,781評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,327評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,084評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,278評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,849評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,495評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,927評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,172評論 1 291
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,010評論 3 396
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,241評論 2 375

推薦閱讀更多精彩內容

  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,726評論 18 399
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,807評論 18 139
  • Spark SQL, DataFrames and Datasets Guide Overview SQL Dat...
    草里有只羊閱讀 18,356評論 0 85
  • 一. Java基礎部分.................................................
    wy_sure閱讀 3,829評論 0 11
  • 阿J是典型的富二代,爹從政娘經商,初三開始交女友,班花校花白富美,不亦樂乎,直到大二看見桃子。桃子還蠻普通的,不美...
    九大人閱讀 265評論 0 1