json教程从入门到使用
json教程从入门到使用
一:入门
简介:
JSON(JavaScriptObject Notation)、轻量级数据交换格式、非常适合于服务器与 JavaScript 的交互。
JSON两种格式:
1、对象
对象是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间使用“,”(逗号)分隔。
2、数组
数组是值(value)的有序集合。一个数组以“[”(左中括号)开始,“]”(右中括号)结束。值之间使用“,”(逗号)分隔。
(具体格式可参照www.json.org、这里只做简略介绍、下方会贴出具体相关)
javascript中的JSON相关:
一:对象型JSON
二:数组型JSON
$(document).ready(function showStudent(){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 +'<br/>');document.write('sno:' + student[0]["sno"] + ' name:' + student[0]["name"] +' age :' + student[0]["age"]+'<br/>' );document.write('sno:' + student[1]["sno"] + ' name:' + student[1]["name"] +' age :' + student[1]["age"]+'<br/>' );document.write('sno:' + student[1]["sno"] + ' name:' + student[1]["name"] +' age :' + student[1]["age"]+'<br/>' );document.write('sno:' + student[2]["sno"] + ' name:' + student[2]["name"] +' age :' + student[2]["age"]+'<br/>' );document.write('sno:' + student[2]["sno"] + ' name:' + student[2]["name"] +' age :' + student[2]["age"]+'<br/>' );});
三:相互嵌套(仅举一种、可自己弄着玩试试)
$(document).ready(function showStudent(){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+'<br/>' );});
补充:至于JSON为什么能这样取得数据的值? It is based on a subset of the JavaScript Programming Language, StandardECMA-262 3rd Edition - December 1999. 它是javascript的一个子集、javascript会对其进行解析(如何实现暂不理会)。
四:json格式的字符串、和json对象(对于什么时候称作json对象不做深究)的区别:
很简单:json格式的字符串、很明显就是一个字符串、只具有字符串的特性和功能。只是格式上看起来像json对象而已、而不具有json对象所具有的功能(比如上面的例子中拿到student对象的某个属性的值、上面是String的话、student.sno能获得sno的值吗?某老师的话:自己动手试试……)。
$(document).ready(function showStudent(){var student = {"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 +'<br/>' );});
注意:别把
typeof(studentJson)+'<br/>
'写成
typeof(studentJson +'<br/>')
这样就成了JSON对象与String拼接了、结果会变成两个string…
JSON格式Str与JSON对象之间的转换
一:Object转换成JSONStr
$(document).ready(function Object2JSONString(){var student = new Student("001","chy");var studentJson = student.toJSONString();document.write(typeof(studentJson) + '<br/>');document.write(studentJson + '<br/>');});//toJOSNString() 可以把json格式的字符串或者Object转换成json对象function Student(sno, name){this.sno = sno;this.name = name;}
二:JSONStr转换成JSON对象
$(document).ready(function str2json () {var studentStr = '{"sno":"001","name":"jack","age":123}';//不推荐、存在安全隐患var studentJson = eval('('+studentStr+')');//缺陷:不能适用于所有的浏览器var studentJson2 = JSON.parse(studentStr);//需下载jquery.json-2.4.js、未实现//var studentJson3 = jQuery.toJSON(studentStr); //document.write(typeof(studentJson3)+'<br/>' );document.write(typeof(studentStr) +'<br/>' );document.write(typeof(studentJson)+'<br/>' );document.write(typeof(studentJson2)+'<br/>' );})
三:JSON对象转换成JSONStr
$(document).ready(function json2str () {var studentJson = {"sno":"001","name":"jack","age":123};//toJSONString()方法需要借助json.js文件(可去官方网站下载)var studentStr = studentJson.toJSONString();var studentStr2 = JSON.stringify(studentJson);document.write(studentStr +'<br/>' );document.write(studentStr2 +'<br/>' );document.write(typeof(studentStr) +'<br/>' );document.write(typeof(studentJson)+'<br/>' );})
JSON遍历
四种遍历方式:
<!DOCTYPE HTML>
<html><script src="jquery.min.js"></script><script type="text/javascript">function firstMethod(){var list1 = [1,3,4];document.write(list1[1]+'<br/>');var list2 = [{"name":"leamiko","xing":"lin"}];document.write(list2[0]["xing"]+'<br/>');document.write(list2[0].xing+'<br/>');document.write("==========================================================="+'<br/>');}function secondMethod(){var value = {"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(var country in value){document.write(country +':<br/>');for(var city in value[country]){document.write(' '+city+':</br>');for(var item in value[country][city]){document.write(' '+value[country][city][item]+':</br>');}}}document.write("==========================================================="+'<br/>');}function thirdMethod(){var value = {"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(var country in value){document.write(country+'<br/>');for(var x in value[country]){document.write('cityname: ' + value[country][x]["name"] + ' item: ' + value[country][x]["item"] + '<br/>');}}document.write("==========================================================="+'<br/>');}function fourthMethod(){var value = {"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(var country in value){document.write(country+'<br/>');for(var i=0; i<value[country].length; i++){document.write('cityname: ' + value[country][i]["name"] + ' item: ' + value[country][i]["item"] + '<br/>');}}document.write("==========================================================="+'<br/>');}$(document).ready=firstMethod();$(document).ready=secondMethod();$(document).ready=thirdMethod();$(document).ready=fourthMethod();</script>
<body></body>
</html>
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
<package name="default" namespace="/" extends="json-default"><action name="jsontest" class="struts2jsonjquery.test.action.JsonJqueryStruts2Action"><!-- 返回单个值的result --><result name="message" type="json"></result><!-- 返回UserInfo对象的 --><result name="userInfo" type="json"></result><!-- 返回List对象的 --><result name="list" type="json"></result><!-- 返回Map对象的 --><result name="map" type="json"></result></action></package>
3、jsp
<%@ page language="java" pageEncoding="GBK"%>
<%String path = request.getContextPath();
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>Struts2+JQuery+JSON</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><script type="text/javascript" src="<%=path %>/js/jquery.js"></script><script type="text/javascript" src="<%=path %>/js/jsonstyle.js"></script></head><body><input id="getMessage" type="button" value="获取单个值"/> <input id="getUserInfo" type="button" value="获取UserInfo对象"/> <input id="getList" type="button" value="获取List对象"/> <input id="getMap" type="button" value="获取Map对象"/> <br><br><br><!-- 要显示信息的层 --><div id="message"></div><form>用户ID:<input name="userInfo.userId" type="text"/><br/>用户名:<input name="userInfo.userName" type="text"/><br/>密 码:<input name="userInfo.password" type="text"/><br><input id="regRe" type="button" value="注册"/></form></body>
</html>
其中的jsonstyle.js代码:
//初始加载页面时
$(document).ready(function(){//为获取单个值的按钮注册鼠标单击事件$("#getMessage").click(function(){$.getJSON("jsontest!returnMessage.action",function(data){//通过.操作符可以从data.message中获得Action中message的值$("#message").html("<font color='red'>"+data.message+"</font>");});});//为获取UserInfo对象按钮添加鼠标单击事件$("#getUserInfo").click(function(){$.getJSON("jsontest!returnUserInfo.action",function(data){//清空显示层中的数据$("#message").html("");//为显示层添加获取到的数据//获取对象的数据用data.userInfo.属性$("#message").append("<div><font color='red'>用户ID:"+data.userInfo.userId+"</font></div>").append("<div><font color='red'>用户名:"+data.userInfo.userName+"</font></div>").append("<div><font color='red'>密码:"+data.userInfo.password+"</font></div>")});});//为获取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("<div>第"+(i+1)+"个用户:</div>").append("<div><font color='red'>用户ID:"+value.userId+"</font></div>").append("<div><font color='red'>用户名:"+value.userName+"</font></div>").append("<div><font color='red'>密码:"+value.password+"</font></div>");});});});//为获取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("<div><font color='red'>用户ID:"+value.userId+"</font></div>").append("<div><font color='red'>用户名:"+value.userName+"</font></div>").append("<div><font color='red'>密码:"+value.password+"</font></div>");});});});//向服务器发送表达数据$("#regRe").click(function(){//把表单的数据进行序列化var params = $("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("<div><font color='red'>用户ID:"+data.userInfo.userId+"</font></div>").append("<div><font color='red'>用户名:"+data.userInfo.userName+"</font></div>").append("<div><font color='red'>密码:"+data.userInfo.password+"</font></div>")}});});
});
4、action
package struts2jsonjquery.test.action;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import struts2jsonjquery.test.entity.UserInfo;import com.opensymphony.xwork2.ActionSupport;public class JsonJqueryStruts2Action extends ActionSupport {private static final long serialVersionUID = 3518833679938898354L;private String message; //使用json返回单个值private UserInfo userInfo; //使用json返回对象private List<UserInfo> userInfosList; //使用josn返回List对象private Map<String,UserInfo> userInfosMap; //使用json返回Map对象//为上面的的属性提供get,Set方法public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public UserInfo getUserInfo() {return userInfo;}public void setUserInfo(UserInfo userInfo) {this.userInfo = userInfo;}public List<UserInfo> getUserInfosList() {return userInfosList;}public void setUserInfosList(List<UserInfo> userInfosList) {this.userInfosList = userInfosList;}public Map<String, UserInfo> getUserInfosMap() {return userInfosMap;}public void setUserInfosMap(Map<String, UserInfo> userInfosMap) {this.userInfosMap = userInfosMap;}/*** <p>* 返回单个值* <p>* @return*/public String returnMessage(){this.message = "成功返回单个值";return "message";}/*** <p>* 返回UserInfo对象* </p>* @return*/public String returnUserInfo(){userInfo = new UserInfo();userInfo.setUserId(10000);userInfo.setUserName("张三");userInfo.setPassword("000000");return "userInfo";}/*** <p>* 返回List对象* </p>* @return*/public String returnList(){userInfosList = new ArrayList<UserInfo>();UserInfo u1 = new UserInfo();u1.setUserId(10000);u1.setUserName("张三");u1.setPassword("000000");UserInfo u2 = new UserInfo();u2.setUserId(10001);u2.setUserName("李四");u2.setPassword("111111");UserInfo u3 = new UserInfo();u3.setUserId(10002);u3.setUserName("王五");u3.setPassword("222222");UserInfo u4 = new UserInfo();u4.setUserId(10003);u4.setUserName("赵六");u4.setPassword("333333");userInfosList.add(u1);userInfosList.add(u2);userInfosList.add(u3);userInfosList.add(u4);return "list";}/*** <p>* 返回Map对象* </p>* @return*/public String returnMap(){userInfosMap = new HashMap<String,UserInfo>();UserInfo u1 = new UserInfo();u1.setUserId(10000);u1.setUserName("张三");u1.setPassword("000000");UserInfo u2 = new UserInfo();u2.setUserId(10001);u2.setUserName("李四");u2.setPassword("111111");UserInfo u3 = new UserInfo();u3.setUserId(10002);u3.setUserName("王五");u3.setPassword("222222");UserInfo u4 = new UserInfo();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";}/*** <p>* 获得对象,也就是通过表达获得对象(异步的)* </P>* @return*/public String gainUserInfo(){System.out.println("用户ID:"+userInfo.getUserId());System.out.println("用户名:"+userInfo.getUserName());System.out.println("密码:"+userInfo.getPassword());return "userInfo";}/*** 获得单个值就不用写了和平常一样*/
}
需要web源码可留下邮箱。。
json教程从入门到使用相关推荐
- JSON Web Token 入门教程
JSON Web Token 入门教程 转载http://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html JSON Web T ...
- ElasticSearch最全详细使用教程:入门、索引管理、映射详解、索引别名、分词器、文档管理、路由、搜索详解...
墨墨导读:之前我们分享了ElasticSearch最全详细使用教程:入门.索引管理.映射详解,本文详细介绍ElasticSearch的索引别名.分词器.文档管理.路由.搜索详解. 一.索引别名 1. ...
- ChatGPT 教程 - 从入门到精通-part2-完整版
文章目录 简介: 1.引言 2.ChatGPT 简介 2.1 什么是 ChatGPT? 2.2 ChatGPT 的应用领域 2.3 ChatGPT 的优势和限制 3.准备工作 3.1 安装 ChatG ...
- python语言入门详解-python初级教程:入门详解
python初级教程:入门详解 Crifan Li 目录 前言 .................................................................... ...
- Android Studio2.0 教程从入门到精通Windows版
系列教程 Android Studio2.0 教程从入门到精通Windows版 - 安装篇 Android Studio2.0 教程从入门到精通Windows版 - 入门篇 Android Studi ...
- grub4dos初级教程-入门篇
grub4dos初级教程-入门篇 2008年04月21日 星期一 15:37 0 为何写此初级教程? 假如你是第一次听说grub,你可能说我不需要grub.那么,你是否用过"一键ghost& ...
- 单片机独立式按键c语言程序,(原创)51单片机C语言程序设计--速学教程实例(入门篇)之独立按键(查询)...
(原创)51单片机C语言程序设计--速学教程实例(入门篇)之独立按键(查询) /************************************************************ ...
- Json Schema快速入门
Json Schema快速入门 JSON 模式是一种基于 JSON 格式定义 JSON 数据结构的规范.它被写在 IETF 草案下并于 2011 年到期.JSON 模式: 描述现有数据格式. 干净的人 ...
- Oracle数据库基础教程:入门其实很简单
为什么80%的码农都做不了架构师?>>> Oracle数据库基础教程:入门其实很简单 Oracle数据库系统是目前最流行的客户/服务器数据库之一.本文集从初学者的角度出发,由浅 ...
最新文章
- GAN性能不稳?这九大技术可“镇住”四类缺陷
- mysql errno : 1146_MySQL_MySQL复制出错 Last_SQL_Errno:1146的解决方法,背景:我们在做数据迁移或者 - phpStudy...
- 413 Request Entity Too Large
- Mysql函数访问oracle,Oracle与MySql函数
- 小爱同学100个奇葩回复_奇葩”订单分享:谁还不是个有故事的同学了?
- 关于搭建wiki镜像和数据库的一些东西
- NodeJS Stream 三:readable
- html编写在线打字通,金山打字在线练习版 怎么修改金山打字通打字速度?
- 计算机窗体视频教程,计算机二级Access2010视频教程
- matlab雷达噪声模型,雷达信号处理MATLAB仿真.doc
- 让硬盘灯不再狂闪,调整Win7系统绝技(转)
- 江苏省政府参事徐惠民莅临聚合数据走访指导
- 成都榆熙:拼多多商家忘记店铺登录密码怎么办?怎么找回?
- 怎样区分细菌性和病毒性感冒
- Android——下载apk文件,并在通知栏显示下载进度
- C语言初学知识准备(Linux方面)
- BZOJ 4888 [Tjoi2017] 异或和
- 185.[USACO Oct08] 挖水井 (第三次考试大整理)
- abaqus unable start analysis job
- mysql front的命令_mysql-front远程连接自己linux服务器上的mysql服务器
热门文章
- 如何更改域控制器的netbios名字
- 多任务编程之进程Process
- tf47:SeqGAN
- Java游戏开发前景
- 良好的编程风格(一)
- Delphi中trim、trimleft以及trimright的用法
- 美国计算机科学奥林匹克竞赛试题,计算机专业留学|USACO:美国的信息学奥林匹克竞赛...
- Linux运维工程师必知的服务器备份工具:Rsnapshot
- Linux——管理网络配置文件、设定ip、网关、DNS
- [原创]解决:Error: php72w-common conflicts with php-common-5.4.16-48.el7.x86_64