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阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,497评论 18 399
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,497评论 18 139
  • Spark SQL, DataFrames and Datasets Guide Overview SQL Dat...
    草里有只羊阅读 18,268评论 0 85
  • 一. Java基础部分.................................................
    wy_sure阅读 3,774评论 0 11
  • 阿J是典型的富二代,爹从政娘经商,初三开始交女友,班花校花白富美,不亦乐乎,直到大二看见桃子。桃子还蛮普通的,不美...
    九大人阅读 248评论 0 1