1.什么是JSON
(1)JSON(Java Script Object Notation)是一种轻量级的数据交换语言,
以文本字符串为基础,且易于让人阅读
XML就是一个重量级的数据交换语言
(2)JSON采用完全独立于任何程序语言的文本格式,使JSON成为理想的数据交换语言
2.struts中使用JSON
引入jar包
struts2-json-plugin-2.3.20
struts配置中将包继承自json-default
result中的type属性设置为json
struts如何找到要转为json的数据?
将要转为json的数据设置为实例变量,并提供get方法,struts插件会扫描action中有get方法的实例变量,并转为json格式。如果指定输出哪些变量,在struts文件中配置返回root
<result type="json">
<param name="root">return_map</param>
</result>
3.JSON实现的三级联动
jsp:
<select id="provinceID" onchange="getCity(this)"> <option >选择省份</option> <option >广东</option> <option >山东</option> </select> <select id="cityID" onchange="getArea(this)"> <option value="">选择城市</option> </select> <select id="areaID" > <option value="">选择区域</option> </select>
js:
function getCity(selEle) { var province = selEle[selEle.selectedIndex].innerHTML; //清空城市下拉框 var cityEle = document.getElementById("cityID"); cityEle.options.length=1; //清空区域下拉框 var areaEle = document.getElementById("areaID"); areaEle.options.length=1; if(province == "选择省份") return ; var ajax = createAJAX(); var method = "POST"; var url = "${pageContext.request.contextPath}/getCity?time=" +new Date().getTime(); ajax.open(method,url); var content = "loc.province="+province; ajax.setRequestHeader("content-type","application/x-www-form-urlencoded"); ajax.send(content); ajax.onreadystatechange = function(){ if(ajax.readyState == 4) { if(ajax.status == 200) { //返回java格式的json,不能被js执行 var jsonJAVA = ajax.responseText; //将java格式的json转成js格式的json var jsonJS = eval("("+jsonJAVA+")"); var array = jsonJS.cityList; for(var i =0;i<array.length;i++){ var option = document.createElement("option"); option.innerHTML = array[i]; cityEle.appendChild(option); } } } } } function getArea(selEle) { var city = selEle[selEle.selectedIndex].innerHTML; //清空区域下拉框 var areaEle = document.getElementById("areaID"); areaEle.options.length=1; if(city == "选择城市") { return; } var ajax = createAJAX(); var method = "POST"; var url = "${pageContext.request.contextPath}/getArea?time=" +new Date().getTime(); ajax.open(method,url); ajax.setRequestHeader("content-type","application/x-www-form-urlencoded"); var content = "loc.city="+city; ajax.send(content); ajax.onreadystatechange = function(){ if(ajax.readyState == 4) { if(ajax.status == 200) { var jsonJAVA = ajax.responseText; var jsonJS = eval("("+jsonJAVA+")"); var array = jsonJS.areaList; for(var i=0;i<array.length;i++){ var option = document.createElement("option"); option.innerHTML = array[i]; areaEle.appendChild(option); } } } } }
struts.xml
<package name="json" extends="json-default"> <action name="getCity" class="jsonAction" method="getCity"> <result name="success" type="json"/> </action> <action name="getArea" class="jsonAction" method="getArea"> <result name="success" type="json"/> </action> </package>
action:
public class JsonAction extends ActionSupport implements RequestAware{ private Map<String,Object> request; @Override public void setRequest(Map<String, Object> map) { this.request = map; } private Location loc; public void setLoc(Location loc) { this.loc = loc; } public Location getLoc() { return loc; } private List<String> cityList; public List<String> getCityList() { return cityList; } // 根据省份获得城市 public String getCity(){ cityList = new ArrayList<String>(); if("广东".equals(loc.getProvince())) { cityList.add("广州"); cityList.add("深圳"); cityList.add("珠海"); } else if("山东".equals(loc.getProvince())) { cityList.add("济南"); cityList.add("枣庄"); cityList.add("青岛"); cityList.add("烟台"); } return SUCCESS; } // 根据城市获取区域 private List<String> areaList; public List<String> getAreaList() { return areaList; } public String getArea(){ areaList = new ArrayList<String>(); if("枣庄".equals(loc.getCity())) { areaList.add("市中区"); areaList.add("山亭区"); areaList.add("台儿庄区"); } return SUCCESS; } }
4.使用第三方工具,将Bean对象、List、Set、Map对象转成JSON
引入jar包 json-lib-2.3-jdk15
@Test public void test1(){ Location location = new Location(); location.setProvince("山东"); location.setCity("枣庄"); JSONArray jsonArray = JSONArray.fromObject(location); System.out.println(jsonArray); //[{"province":"山东","city":"枣庄"}] } @Test public void test2(){ ArrayList<Location> locs = new ArrayList<>(); Location location = new Location(); location.setProvince("山东"); location.setCity("枣庄"); Location location2 = new Location(); location2.setProvince("广东"); location2.setCity("广州"); locs.add(location); locs.add(location2); JSONArray jsonArray = JSONArray.fromObject(locs); System.out.println(jsonArray); //[{"province":"山东","city":"枣庄"},{"province":"广东","city":"广州"}] } @Test public void test3(){ Set<Location> locs = new LinkedHashSet<>(); Location location = new Location(); location.setProvince("山东"); location.setCity("枣庄"); Location location2 = new Location(); location2.setProvince("广东"); location2.setCity("广州"); locs.add(location); locs.add(location2); JSONArray jsonArray = JSONArray.fromObject(locs); System.out.println(jsonArray); //[{"province":"山东","city":"枣庄"},{"province":"广东","city":"广州"}] } @Test public void test4(){ Department department = new Department(); department.setId(10); Employee emp1 = new Employee(); emp1.setEmpName("zhang"); emp1.setSalary(1000); Employee emp2= new Employee(); emp2.setEmpName("lisi"); emp2.setSalary(2000); List<Employee> employeeList = new ArrayList<Employee>(); employeeList.add(emp1); employeeList.add(emp2); department.setEmps(employeeList); JSONArray jsonArray = JSONArray.fromObject(department); System.out.println(jsonArray); //[{ // "emps":[{"empId":0,"empName":"zhang","dept":null,"salary":1000}, // {"empId":0,"empName":"lisi","dept":null,"salary":2000}], // "id":10 // }] }
map转为json
private static void map2json() { List<City> cityList = new ArrayList<City>(); cityList.add(new City(1,"中山")); cityList.add(new City(2,"佛山")); Map<String,Object> map = new LinkedHashMap<String,Object>(); map.put("total",cityList.size());//表示集合的长度 map.put("rows",cityList);//rows表示集合 JSONArray jSONArray = JSONArray.fromObject(map); String jsonJAVA = jSONArray.toString(); System.out.println(jsonJAVA); //[{"total":2,"rows":[{"id":1,"name":"中山"},{"id":2,"name":"佛山"}]}] jsonJAVA = jsonJAVA.substring(1,jsonJAVA.length()-1); System.out.println(jsonJAVA); }
5.JSON的特点
(1)在客户端,直接使用JavaScript语言解析JSON,无需第三方jar包
(2)本质上,就是一个文本,只是该文本有特定的书写格式
(3)可以使用第三方工具,将JavaBean对象或者List/Set/Map<JavaBean>对象转成JSON
(4)优点:JSON与XML很相似,但是它更加轻巧,服务器只需发送一个html普通字符串,不用发送复杂的xml格式文档了
(5)缺点:语法过于严谨,初学者可能觉得代码不易读,写错一点都不行
(6)JSON本质上,就是用JS语法写的特殊文本记号,用JS可以直接解析
6.JSON数组及遍历
/*用JSON语法创建一个一维数组,存入string类型的姓名,再迭代*/ var nameArray = ["哈哈","呵呵","嘻嘻","都都"];//js对象 var $nameArray = $(nameArray);//jquery对象 $nameArray.each(function(){ //this表示数组中每一个元素,this属性js对象,this代表string类型 alert(this); }); //用JSON语法创建一个一维数组,存入object类型的姓名和薪水,再迭代 var nameArray = [ { name : "哈哈", sal : 6000 }, { name : "嘿嘿", sal : 7000 }, { name : "笨笨", sal : 8000 } ]; var $nameArray = $(nameArray); $nameArray.each(function(){ //this代表object类型 alert(this.name + ":"+this.sal); });