首页 > 代码库 > json与java对象的转换,以及struts2对json的支持,实现ajax技术
json与java对象的转换,以及struts2对json的支持,实现ajax技术
这两天学的东西有点多,今天抽个时间写下来,以此作为激励,这两天学了json,ajax,jQuery
一、使用第三方的工具java转换为json类型
首先就是java类型转换为json对象,首先要导入第三方工具包:
准备导入第三方jar包:
》commons-beanutils-1.7.0.jar
》commons-collections-3.1.jar
》commons-lang-2.5.jar
》commons-logging-1.1.1.jar
》ezmorph-1.0.3.jar
》json-lib-2.1-jdk15.jar
转换的方法如下:
(1)JavaBean----->JSON
》JSONArray jsonArray = JSONArray.fromObject(city);
》String jsonJAVA = jsonArray.toString();
(2)List<JavaBean>----->JSON
》JSONArray jsonArray = JSONArray.fromObject(cityList);
》String jsonJAVA = jsonArray.toString();
(3)List<String>----->JSON
》JSONArray jsonArray = JSONArray.fromObject(stringList);
》String jsonJAVA = jsonArray.toString();
(4)Set<JavaBean>----->JSON
》JSONArray jsonArray = JSONArray.fromObject(citySet);
》String jsonJAVA = jsonArray.toString();
(5)Map<String,Object>----->JSON
》JSONArray jsonArray = JSONArray.fromObject(map);
》String jsonJAVA = jsonArray.toString();
public static void javabean2Json() { City city = new City(1,"广州"); JSONArray jsonArray = JSONArray.fromObject(city); String jsonJAVA = jsonArray.toString(); System.out.println(jsonJAVA); //[{"id":1,"name":"广州"}] } public static void list2json() { List<City> cityList = new ArrayList<City>(); cityList.add(new City(1,"广州")); cityList.add(new City(2,"深圳")); Province province = new Province(1,"广东",cityList); //[{"id":1,"cityList":[{"id":1,"name":"广州"},{"id":2,"name":"深圳"}],"name":"广东"}] JSONArray jsonArray = JSONArray.fromObject(province); String jsonJAVA = jsonArray.toString(); System.out.println(jsonJAVA); //List集合[{"id":1,"name":"广州"},{"id":2,"name":"深圳"}] } public static void set2json() { Set<City> citySet= new HashSet<City>(); citySet.add(new City(1,"广州")); citySet.add(new City(2,"深圳")); JSONArray jsonArray = JSONArray.fromObject(citySet); String jsonJAVA = jsonArray.toString(); System.out.println(jsonJAVA); //[{"id":1,"name":"广州"},{"id":2,"name":"深圳"}] } public static void map2json() { List<City> cityList = new ArrayList<City>(); cityList.add(new City(1,"广州")); cityList.add(new City(2,"深圳")); Map<String,Object> map = new HashMap<String,Object>(); map.put("total", cityList.size());//表示集合的长度 map.put("rows", cityList);//表示集合 /** * [{"total":2,"rows":[{"id":1,"name":"广州"},{"id":2,"name":"深圳"}]}] */ JSONArray jsonArray = JSONArray.fromObject(map); String jsonJAVA = jsonArray.toString(); jsonJAVA = jsonJAVA.substring(1,jsonJAVA.length()-1); System.out.println(jsonJAVA); //[{"id":1,"name":"广州"},{"id":2,"name":"深圳"}] } public static void main(String[] args) { // TODO Auto-generated method stub // javabean2Json(); // list2json(); // set2json(); map2json(); }
注意的是这里json全是java格式,必须转换为javascript所支持的json格式.
注意:JS可以直接解析JSON格式的文本,前提是:该JSON必须采用JS格式书写的才行,如果该JSON是采用Java格式写的,必须使用eval()函数转换后,方可被JS解析,该eval("")函数接收一个字符串格式的内容。
二 、使用struts2自动将java对象转换为json
1)导入struts2的jar包,主要是一些核心包,
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
commons-lang3-3.1.jar
freemarker-2.3.19.jar
javassist-3.11.0.GA.jar
ognl-3.0.5.jar
struts2-core-2.3.4.1.jar
xwork-core-2.3.4.1.jar
还有一个struts2对json支持的插件包:struts2-json-plugin-2.3.1.1.jar
2)配置web.xml
<!-- 配置拦截器 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
配置struts.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- 配置struts2 --> <!--<package name="checknode" extends="struts-default" namespace="/user"> <action name="check" class="cn.itcast.js_02.checkcode.CheckcodeAction" method="check"> </action> </package>--> <package name="province" extends="json-default" namespace="/"> <!-- 配置全局结果 --> <global-results> <result name="success" type="json"></result> </global-results> <action name="findCityByProvince" class="cn.itcast.js_02.provincecityarea.ProvinceCityArea" method="findCityByProvince"> </action> <action name="findAreaByCity" class="cn.itcast.js_02.provincecityarea.ProvinceCityArea" method="findAreaByCity"> </action> </package> </struts>
3)javabean 代码:
package cn.itcast.js_02.provincecityarea; public class Bean { private String province; private String city; public Bean() { // TODO Auto-generated constructor stub } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
Action代码:
package cn.itcast.js_02.provincecityarea; import java.util.ArrayList; import java.util.List; import com.opensymphony.xwork2.ActionSupport; public class ProvinceCityArea extends ActionSupport { private Bean bean; public void setBean(Bean bean) { this.bean = bean; } public Bean getBean() { return bean; } public String findCityByProvince() throws Exception { // TODO Auto-generated method stub cityList = new ArrayList<String>(); if("湖北".equals(bean.getProvince())) { cityList.add("武汉"); cityList.add("孝感"); cityList.add("黄冈"); }else if("湖南".equals(bean.getProvince())) { cityList.add("长沙"); cityList.add("株洲"); cityList.add("岳阳"); cityList.add("湖南"); }else if("江西".equals(bean.getProvince())) { cityList.add("南昌"); cityList.add("南昌"); cityList.add("南昌"); cityList.add("南昌"); } //配置让struts2自动将List/Set/Map<String>转换为JSON文本 return this.SUCCESS; } /** * 通过城市查找区域 * @return * @throws Exception */ public String findAreaByCity() throws Exception { // TODO Auto-generated method stub areaList = new ArrayList<String>(); if("武汉".equals(bean.getCity())) { areaList.add("AA"); areaList.add("BB"); areaList.add("CC"); }else if("南昌".equals(bean.getCity())) { areaList.add("DD"); areaList.add("EE"); areaList.add("FF"); }else if("长沙".equals(bean.getCity())) { areaList.add("GG"); areaList.add("HH"); areaList.add("II"); } //配置让struts2自动将List/Set/Map<String>转换为JSON文本 return this.SUCCESS; } private List<String> cityList; private List<String> areaList; public List<String> getAreaList() { return areaList; } public List<String> getCityList() { return this.cityList; } }
jsp代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>struts2实现三级联查询</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"> <!-- <link rel="stylesheet" type="text/css" href="http://www.mamicode.com/styles.css"> --> </head> <body> <select id="provinceID" style="width:111px"> <option>请选择省份</option> <option>湖北</option> <option>湖南</option> <option>江西</option> </select> <select id="cityID" style="width:111px"> <option>请选择城市</option> </select> <select id="areaID" style="width:111px"> <option>请选择区域</option> </select> <script type="text/javascript" src="js/ajax.js"></script> <script type="text/javascript"> document.getElementById("provinceID").onchange = function() { var province = this[this.selectedIndex].innerHTML; //清除之前的样式 var cityElement = document.getElementById("cityID"); cityElement.options.length = 1; //当省份发生变化时,区域也会发生变化 var areaElement = document.getElementById("areaID"); areaElement.options.length = 1; if("选择省份"!=province) { //NO1) var ajax = createAjax(); //NO2) var method = "POST"; var url = "${pageContext.request.contextPath}/findCityByProvince?time="+new Date().getTime(); ajax.open(method, url); //NO3) ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded"); //NO4) var content = "bean.province="+province; ajax.send(content); //------------------------->等待 //NO5) ajax.onreadystatechange = function() { if(ajax.readyState == 4) { if(ajax.status == 200) { //NO6)返回JAVA var jsonJAVA = ajax.responseText; var p = eval("("+jsonJAVA+")"); var array = p.cityList; var size = array.length; for(var i=0;i<size;i++) { var city=array[i]; var option = document.createElement("option"); option.innerHTML = city; cityElement.appendChild(option); } } } } } } document.getElementById("cityID").onchange = function() { var city = this[this.selectedIndex].innerHTML; //清除之前的数据 var areaElement = document.getElementById("areaID"); areaElement.options.length = 1; if("请选择城市"!=city) { //NO1) var ajax = createAjax(); //MO2) var method = "POST"; var url = "${pageContext.request.contextPath}/findAreaByCity?time="+new Date().getTime(); ajax.open(method,url); //NO3) ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded"); //NO4) var content = "bean.city="+city; ajax.send(content); //----------------------等待 ajax.onreadystatechange = function() { //NO5) if(ajax.readyState == 4) { if(ajax.status == 200) { //NO6) var jsonJAVA = ajax.responseText; var jsonJS = eval("("+jsonJAVA+")"); var array = jsonJS.areaList; var size = array.length; for(var i=0;i<size;i++) { var area = array[i]; var option = document.createElement("option"); option.innerHTML = area; areaElement.appendChild(option); } } } } } } </script> </body> <form action="" enctype="application/x-www-form-urlencoded"></form> </html>
在这中间出了一些问题,大部分是因为写错了方法名称或属性名例如:ajax.onreadystatechange
最后再附上源码地址:https://github.com/blench/js_day02.git
json与java对象的转换,以及struts2对json的支持,实现ajax技术