package com.mai.json;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.ezmorph.Morpher;
import net.sf.ezmorph.MorpherRegistry;
import net.sf.ezmorph.bean.BeanMorpher;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.junit.Test;
public class JsonLibTest {
/*
* 普通类型、List、Collection等都是用JSONArray解析
*
* Map、自定义类型是用JSONObject解析
* 可以将Map理解成一个对象,里面的key/value对可以理解成对象的属性/属性值
* 即{key1:value1,key2,value2......}
*
* 1.JSONObject是一个name:values集合,通过它的get(key)方法取得的是key后对应的value部分(字符串)
* 通过它的getJSONObject(key)可以取到一个JSONObject,--> 转换成map,
* 通过它的getJSONArray(key) 可以取到一个JSONArray ,
*
*
*/
//一般数组转换成JSON
@Test
public void testArrayToJSON(){
boolean[] boolArray = new boolean[]{true,false,true};
JSONArray jsonArray = JSONArray.fromObject( boolArray );
System.out.println( jsonArray );
// prints [true,false,true]
}
//Collection对象转换成JSON
@Test
public void testListToJSON(){
List list = new ArrayList();
list.add( "first" );
list.add( "second" );
JSONArray jsonArray = JSONArray.fromObject( list );
System.out.println( jsonArray );
// prints ["first","second"]
}
//字符串json转换成json, 根据情况是用JSONArray或JSONObject
@Test
public void testJsonStrToJSON(){
JSONArray jsonArray = JSONArray.fromObject( "['json','is','easy']" );
System.out.println( jsonArray );
// prints ["json","is","easy"]
}
//Map转换成json, 是用jsonObject
@Test
public void testMapToJSON(){
Map map = new HashMap();
map.put( "name", "json" );
map.put( "bool", Boolean.TRUE );
map.put( "int", new Integer(1) );
map.put( "arr", new String[]{"a","b"} );
map.put( "func", "function(i){ return this.arr[i]; }" );
JSONObject jsonObject = JSONObject.fromObject( map );
System.out.println( jsonObject );
}
//复合类型bean转成成json
@Test
public void testBeadToJSON(){
MyBean bean = new MyBean();
bean.setId("001");
bean.setName("银行卡");
bean.setDate(new Date());
List cardNum = new ArrayList();
cardNum.add("农行");
cardNum.add("工行");
cardNum.add("建行");
cardNum.add(new Person("test"));
bean.setCardNum(cardNum);
JSONObject jsonObject = JSONObject.fromObject(bean);
System.out.println(jsonObject);
}
//普通类型的json转换成对象
@Test
public void testJSONToObject() throws Exception{
String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";
JSONObject jsonObject = JSONObject.fromObject( json );
System.out.println(jsonObject);
Object bean = JSONObject.toBean( jsonObject );
assertEquals( jsonObject.get( "name" ), PropertyUtils.getProperty( bean, "name" ) );
assertEquals( jsonObject.get( "bool" ), PropertyUtils.getProperty( bean, "bool" ) );
assertEquals( jsonObject.get( "int" ), PropertyUtils.getProperty( bean, "int" ) );
assertEquals( jsonObject.get( "double" ), PropertyUtils.getProperty( bean, "double" ) );
assertEquals( jsonObject.get( "func" ), PropertyUtils.getProperty( bean, "func" ) );
System.out.println(PropertyUtils.getProperty(bean, "name"));
System.out.println(PropertyUtils.getProperty(bean, "bool"));
System.out.println(PropertyUtils.getProperty(bean, "int"));
System.out.println(PropertyUtils.getProperty(bean, "double"));
System.out.println(PropertyUtils.getProperty(bean, "func"));
System.out.println(PropertyUtils.getProperty(bean, "array"));
List arrayList = (List)JSONArray.toCollection(jsonObject.getJSONArray("array"));
for(Object object : arrayList){
System.out.println(object);
}
}
//将json解析成复合类型对象, 包含List
@Test
public void testJSONToBeanHavaList(){
String json = "{list:[{name:'test1'},{name:'test2'}],map:{test1:{name:'test1'},test2:{name:'test2'}}}";
// String json = "{list:[{name:'test1'},{name:'test2'}]}";
Map classMap = new HashMap();
classMap.put("list", Person.class);
MyBeanWithPerson diyBean = (MyBeanWithPerson)JSONObject.toBean(JSONObject.fromObject(json),MyBeanWithPerson.class , classMap);
System.out.println(diyBean);
List list = diyBean.getList();
for(Object o : list){
if(o instanceof Person){
Person p = (Person)o;
System.out.println(p.getName());
}
}
}
//将json解析成复合类型对象, 包含Map
@Test
public void testJSONToBeanHavaMap(){
//把Map看成一个对象
String json = "{list:[{name:'test1'},{name:'test2'}],map:{testOne:{name:'test1'},testTwo:{name:'test2'}}}";
Map classMap = new HashMap();
classMap.put("list", Person.class);
classMap.put("map", Map.class);
//使用暗示,直接将json解析为指定自定义对象,其中List完全解析,Map没有完全解析
MyBeanWithPerson diyBean = (MyBeanWithPerson)JSONObject.toBean(JSONObject.fromObject(json),MyBeanWithPerson.class , classMap);
System.out.println(diyBean);
System.out.println("do the list release");
List<Person> list = diyBean.getList();
for(Person o : list){
Person p = (Person)o;
System.out.println(p.getName());
}
System.out.println("do the map release");
//先往注册器中注册变换器,需要用到ezmorph包中的类
MorpherRegistry morpherRegistry = JSONUtils.getMorpherRegistry();
Morpher dynaMorpher = new BeanMorpher( Person.class, morpherRegistry);
morpherRegistry.registerMorpher( dynaMorpher );
Map map = diyBean.getMap();
/*这里的map没进行类型暗示,故按默认的,里面存的为net.sf.ezmorph.bean.MorphDynaBean类型的对象*/
System.out.println(map);
/*输出:
{testOne=net.sf.ezmorph.bean.MorphDynaBean@f73c1[
{name=test1}
], testTwo=net.sf.ezmorph.bean.MorphDynaBean@186c6b2[
{name=test2}
]}
*/
List<Person> output = new ArrayList();
for( Iterator i = map.values().iterator(); i.hasNext(); ){
//使用注册器对指定DynaBean进行对象变换
output.add( (Person)morpherRegistry.morph( Person.class, i.next() ) );
}
for(Person p : output){
System.out.println(p.getName());
/*输出:
test1
test2
*/
}
}
}
1、DTO:Data Transfer Object,数据传送对象
2、对于日期格式的问题,也已经处理
3、json-lib-2.2.2-jdk13.jar (2.1在日期数组 json->java有问题)
工具类JsonUtil代码如下:
Java代码
public class JsonUtil {
/**页面传至后台时,json数据在request的参数名称*/
public final static String JSON_ATTRIBUTE = "json";
public final static String JSON_ATTRIBUTE1 = "json1";
public final static String JSON_ATTRIBUTE2 = "json2";
public final static String JSON_ATTRIBUTE3 = "json3";
public final static String JSON_ATTRIBUTE4 = "json4";
/**
* 从一个JSON 对象字符格式中得到一个java对象,形如:
* {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}}
* @param object
* @param clazz
* @return
*/
public static Object getDTO(String jsonString, Class clazz){
JSONObject jsonObject = null;
try{
setDataFormat2JAVA();
jsonObject = JSONObject.fromObject(jsonString);
}catch(Exception e){
e.printStackTrace();
}
return JSONObject.toBean(jsonObject, clazz);
}
/**
* 从一个JSON 对象字符格式中得到一个java对象,其中beansList是一类的集合,形如:
* {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...},
* beansList:[{}, {}, ...]}
* @param jsonString
* @param clazz
* @param map 集合属性的类型 (key : 集合属性名, value : 集合属性类型class) eg: ("beansList" : Bean.class)
* @return
*/
public static Object getDTO(String jsonString, Class clazz, Map map){
JSONObject jsonObject = null;
try{
setDataFormat2JAVA();
jsonObject = JSONObject.fromObject(jsonString);
}catch(Exception e){
e.printStackTrace();
}
return JSONObject.toBean(jsonObject, clazz, map);
}
/**
* 从一个JSON数组得到一个java对象数组,形如:
* [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...]
* @param object
* @param clazz
* @return
*/
public static Object[] getDTOArray(String jsonString, Class clazz){
setDataFormat2JAVA();
JSONArray array = JSONArray.fromObject(jsonString);
Object[] obj = new Object[array.size()];
for(int i = 0; i < array.size(); i++){
JSONObject jsonObject = array.getJSONObject(i);
obj[i] = JSONObject.toBean(jsonObject, clazz);
}
return obj;
}
/**
* 从一个JSON数组得到一个java对象数组,形如:
* [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...]
* @param object
* @param clazz
* @param map
* @return
*/
public static Object[] getDTOArray(String jsonString, Class clazz, Map map){
setDataFormat2JAVA();
JSONArray array = JSONArray.fromObject(jsonString);
Object[] obj = new Object[array.size()];
for(int i = 0; i < array.size(); i++){
JSONObject jsonObject = array.getJSONObject(i);
obj[i] = JSONObject.toBean(jsonObject, clazz, map);
}
return obj;
}
/**
* 从一个JSON数组得到一个java对象集合
* @param object
* @param clazz
* @return
*/
public static List getDTOList(String jsonString, Class clazz){
setDataFormat2JAVA();
JSONArray array = JSONArray.fromObject(jsonString);
List list = new ArrayList();
for(Iterator iter = array.iterator(); iter.hasNext();){
JSONObject jsonObject = (JSONObject)iter.next();
list.add(JSONObject.toBean(jsonObject, clazz));
}
return list;
}
/**
* 从一个JSON数组得到一个java对象集合,其中对象中包含有集合属性
* @param object
* @param clazz
* @param map 集合属性的类型
* @return
*/
public static List getDTOList(String jsonString, Class clazz, Map map){
setDataFormat2JAVA();
JSONArray array = JSONArray.fromObject(jsonString);
List list = new ArrayList();
for(Iterator iter = array.iterator(); iter.hasNext();){
JSONObject jsonObject = (JSONObject)iter.next();
list.add(JSONObject.toBean(jsonObject, clazz, map));
}
return list;
}
/**
* 从json HASH表达式中获取一个map,该map支持嵌套功能
* 形如:{"id" : "johncon", "name" : "小强"}
* 注意commons-collections版本,必须包含org.apache.commons.collections.map.MultiKeyMap
* @param object
* @return
*/
public static Map getMapFromJson(String jsonString) {
setDataFormat2JAVA();
JSONObject jsonObject = JSONObject.fromObject(jsonString);
Map map = new HashMap();
for(Iterator iter = jsonObject.keys(); iter.hasNext();){
String key = (String)iter.next();
map.put(key, jsonObject.get(key));
}
return map;
}
/**
* 从json数组中得到相应java数组
* json形如:["123", "456"]
* @param jsonString
* @return
*/
public static Object[] getObjectArrayFromJson(String jsonString) {
JSONArray jsonArray = JSONArray.fromObject(jsonString);
return jsonArray.toArray();
}
/**
* 把数据对象转换成json字符串
* DTO对象形如:{"id" : idValue, "name" : nameValue, ...}
* 数组对象形如:[{}, {}, {}, ...]
* map对象形如:{key1 : {"id" : idValue, "name" : nameValue, ...}, key2 : {}, ...}
* @param object
* @return
*/
public static String getJSONString(Object object) throws Exception{
String jsonString = null;
//日期值处理器
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(java.util.Date.class, new JsonDateValueProcessor());
if(object != null){
if(object instanceof Collection || object instanceof Object[]){
jsonString = JSONArray.fromObject(object, jsonConfig).toString();
}else{
jsonString = JSONObject.fromObject(object, jsonConfig).toString();
}
}
return jsonString == null ? "{}" : jsonString;
}
private static void setDataFormat2JAVA(){
//设定日期转换格式
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"}));
}
public static void main(String[] arg) throws Exception{
String s = "{status : 'success'}";
System.out.println(" object : " + JsonUtil.getJSONString(s));
}
}
public class JsonUtil {
/**页面传至后台时,json数据在request的参数名称*/
public final static String JSON_ATTRIBUTE = "json";
public final static String JSON_ATTRIBUTE1 = "json1";
public final static String JSON_ATTRIBUTE2 = "json2";
public final static String JSON_ATTRIBUTE3 = "json3";
public final static String JSON_ATTRIBUTE4 = "json4";
/**
* 从一个JSON 对象字符格式中得到一个java对象,形如:
* {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...}}
* @param object
* @param clazz
* @return
*/
public static Object getDTO(String jsonString, Class clazz){
JSONObject jsonObject = null;
try{
setDataFormat2JAVA();
jsonObject = JSONObject.fromObject(jsonString);
}catch(Exception e){
e.printStackTrace();
}
return JSONObject.toBean(jsonObject, clazz);
}
/**
* 从一个JSON 对象字符格式中得到一个java对象,其中beansList是一类的集合,形如:
* {"id" : idValue, "name" : nameValue, "aBean" : {"aBeanId" : aBeanIdValue, ...},
* beansList:[{}, {}, ...]}
* @param jsonString
* @param clazz
* @param map 集合属性的类型 (key : 集合属性名, value : 集合属性类型class) eg: ("beansList" : Bean.class)
* @return
*/
public static Object getDTO(String jsonString, Class clazz, Map map){
JSONObject jsonObject = null;
try{
setDataFormat2JAVA();
jsonObject = JSONObject.fromObject(jsonString);
}catch(Exception e){
e.printStackTrace();
}
return JSONObject.toBean(jsonObject, clazz, map);
}
/**
* 从一个JSON数组得到一个java对象数组,形如:
* [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...]
* @param object
* @param clazz
* @return
*/
public static Object[] getDTOArray(String jsonString, Class clazz){
setDataFormat2JAVA();
JSONArray array = JSONArray.fromObject(jsonString);
Object[] obj = new Object[array.size()];
for(int i = 0; i < array.size(); i++){
JSONObject jsonObject = array.getJSONObject(i);
obj[i] = JSONObject.toBean(jsonObject, clazz);
}
return obj;
}
/**
* 从一个JSON数组得到一个java对象数组,形如:
* [{"id" : idValue, "name" : nameValue}, {"id" : idValue, "name" : nameValue}, ...]
* @param object
* @param clazz
* @param map
* @return
*/
public static Object[] getDTOArray(String jsonString, Class clazz, Map map){
setDataFormat2JAVA();
JSONArray array = JSONArray.fromObject(jsonString);
Object[] obj = new Object[array.size()];
for(int i = 0; i < array.size(); i++){
JSONObject jsonObject = array.getJSONObject(i);
obj[i] = JSONObject.toBean(jsonObject, clazz, map);
}
return obj;
}
/**
* 从一个JSON数组得到一个java对象集合
* @param object
* @param clazz
* @return
*/
public static List getDTOList(String jsonString, Class clazz){
setDataFormat2JAVA();
JSONArray array = JSONArray.fromObject(jsonString);
List list = new ArrayList();
for(Iterator iter = array.iterator(); iter.hasNext();){
JSONObject jsonObject = (JSONObject)iter.next();
list.add(JSONObject.toBean(jsonObject, clazz));
}
return list;
}
/**
* 从一个JSON数组得到一个java对象集合,其中对象中包含有集合属性
* @param object
* @param clazz
* @param map 集合属性的类型
* @return
*/
public static List getDTOList(String jsonString, Class clazz, Map map){
setDataFormat2JAVA();
JSONArray array = JSONArray.fromObject(jsonString);
List list = new ArrayList();
for(Iterator iter = array.iterator(); iter.hasNext();){
JSONObject jsonObject = (JSONObject)iter.next();
list.add(JSONObject.toBean(jsonObject, clazz, map));
}
return list;
}
/**
* 从json HASH表达式中获取一个map,该map支持嵌套功能
* 形如:{"id" : "johncon", "name" : "小强"}
* 注意commons-collections版本,必须包含org.apache.commons.collections.map.MultiKeyMap
* @param object
* @return
*/
public static Map getMapFromJson(String jsonString) {
setDataFormat2JAVA();
JSONObject jsonObject = JSONObject.fromObject(jsonString);
Map map = new HashMap();
for(Iterator iter = jsonObject.keys(); iter.hasNext();){
String key = (String)iter.next();
map.put(key, jsonObject.get(key));
}
return map;
}
/**
* 从json数组中得到相应java数组
* json形如:["123", "456"]
* @param jsonString
* @return
*/
public static Object[] getObjectArrayFromJson(String jsonString) {
JSONArray jsonArray = JSONArray.fromObject(jsonString);
return jsonArray.toArray();
}
/**
* 把数据对象转换成json字符串
* DTO对象形如:{"id" : idValue, "name" : nameValue, ...}
* 数组对象形如:[{}, {}, {}, ...]
* map对象形如:{key1 : {"id" : idValue, "name" : nameValue, ...}, key2 : {}, ...}
* @param object
* @return
*/
public static String getJSONString(Object object) throws Exception{
String jsonString = null;
//日期值处理器
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.registerJsonValueProcessor(java.util.Date.class, new JsonDateValueProcessor());
if(object != null){
if(object instanceof Collection || object instanceof Object[]){
jsonString = JSONArray.fromObject(object, jsonConfig).toString();
}else{
jsonString = JSONObject.fromObject(object, jsonConfig).toString();
}
}
return jsonString == null ? "{}" : jsonString;
}
private static void setDataFormat2JAVA(){
//设定日期转换格式
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"}));
}
public static void main(String[] arg) throws Exception{
String s = "{status : 'success'}";
System.out.println(" object : " + JsonUtil.getJSONString(s));
}
}
对于java对象转换成json数据格式时,要对日期格式化常用格式,类:JsonDateValueProcessor
Java代码
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
/*
* @author johncon
* 创建日期 2008-9-10
* json日期值处理器
*/
public class JsonDateValueProcessor implements JsonValueProcessor {
private String format = "yyyy-MM-dd HH:mm:ss";
public JsonDateValueProcessor() {
}
public JsonDateValueProcessor(String format) {
this.format = format;
}
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
return process(value, jsonConfig);
}
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
return process(value, jsonConfig);
}
private Object process( Object value, JsonConfig jsonConfig ) {
if (value instanceof Date) {
String str = new SimpleDateFormat(format).format((Date) value);
return str;
}
return value == null ? null : value.toString();
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
/*
* @author johncon
* 创建日期 2008-9-10
* json日期值处理器
*/
public class JsonDateValueProcessor implements JsonValueProcessor {
private String format = "yyyy-MM-dd HH:mm:ss";
public JsonDateValueProcessor() {
}
public JsonDateValueProcessor(String format) {
this.format = format;
}
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
return process(value, jsonConfig);
}
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
return process(value, jsonConfig);
}
private Object process( Object value, JsonConfig jsonConfig ) {
if (value instanceof Date) {
String str = new SimpleDateFormat(format).format((Date) value);
return str;
}
return value == null ? null : value.toString();
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
对于对象中有明确类型的对象属性,可不管;但对象中有集合属性的,由于类型不明确,所以要先明确类型:
Java代码
String jsonString = request.getParameter("json");
//增加对象中的集合属性的类型以及对象元素中的对象属性的集合属性的类型
Map clazzMap = new HashMap();
//secondItems是FirstDTO里的集合属性
clazzMap.put("secondItems", SecondDTO.class);
//thirdItems是SecondDTO里的集合属性
clazzMap.put("thirdItems", ThirdDTO.class);
FirstDTO firstDTO = (FirstDTO)JsonUtil.getDTO(jsonString, FirstDTO.class, clazzMap);
Struts2的XML配置说明
<result type="json">
<!-- 这里指定将被Struts2序列化的属性,该属性在action中必须有对应的getter方法 -->
<!-- 默认将会序列所有有返回值的getter方法的值,而无论该方法是否有对应属性 -->
<param name="root">dataMap</param>
<!-- 指定是否序列化空的属性 -->
<param name="excludeNullProperties">true</param>
<!-- 这里指定将序列化dataMap中的那些属性 -->
<param name="includeProperties">userList.*</param>
<!-- 这里指定将要从dataMap中排除那些属性,这些排除的属性将不被序列化,一般不与上边的参数配置同时出现 -->
<param name="excludeProperties">SUCCESS</param>
</result>
<!-- 封装所以的get开头的方法 -->
<result type="json" name="user">
</result>
<!-- 只包含user.id属性 -->
<result type="json" name="user">
<param name="includeProperties">
user\.id,
list\[\d+\]\.Id, list\[\d+\]\.userName //正则表达式(以逗号隔开)
</param>
</result>
<!-- 不包含user属性 -->
<result type="json" name="list">
<param name="excludeProperties">
user
</param>
</result>
<!-- 根对象只包含user -->
<result type="json">
<param name="root">
user
</param>
</result>
<!-- includeProperties 直接返回对象的json数据,前台不需要eval转换,<param name="root">result</param>则不同,需要前台进行eval转换 -->
<!-- "root"对象中父类的field(属性)不会(会?) 默认存放到 JSON数据中,如果不想这样做,需要在配置时指定 ignoreHierarchy 为 false: -->
<result type="json">
<pa
我们只要输出person对象的name属性值,配置如下
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
2
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
3
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
<result type="json"> <param name="root">person.name</param> </result>
5.2. excludeNullProperties 参数:表示是否去掉空值, 默认值是false,如果设置为true会自动将为空的值过滤,只输出不为空的值。
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
2
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
3
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
4
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
<result type="json"> <param name="excludeNullProperties">true</param> </result>
5.3. ignoreHierarchy 参数:表示是否忽略等级,也就是继承关系,比如:TestAction继承于BaseAction,那么TestAction中返回的json字符串默认是不会包含父类BaseAction的属性值,ignoreHierarchy值默认为true,设置为false后会将父类和子类的属性一起返回。
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
2
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
3
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
<result type="json"> <param name="ignoreHierarchy">false</param> </result>
5.4. includeProperties 参数:输出结果中需要包含的属性值,这里正则表达式和属性名匹配,可以用“,”分割填充多个正则表达式。
如:输出person的所有属性
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
2
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
3
![](https://i-blog.csdnimg.cn/blog_migrate/4f1150b881333f12a311ae9ef34da474.gif)
<!-- 返回的是一个user对象 user对象(id,name,pass) --> |
14 | < result name = "findByDarkName" type = "json" > |
15 | <!-- param参数的配置,includeProperties --> |
16 | < param name = "includeProperties" > |
17 | list\[\d+\]\.id, list\[\d+\]\.name, list\[\d+\]\.pass |
18 | </ param > |
19 | </ result > |
Struts2+JQuery+Json及JQuery相关插件的例子
注意事项:
1.开发时,应将工程及相应的页面数据库编码均设为:utf8解决乱码问题;
2.当前开发版本为struts2.1.8,不同的struts2版本会有不同的jar包需要引入,具体见readme.txt
3.autocomplete插件不是很完善,尚不能处理json数据;弹出层框架只针对图片(可修改格式适应其它形式)
readme.txt:
- 1.JQuery的Ajax实现并与struts2的结合
- 2.配置过程:
- a.新建web项目;
- b.修改web.xml文件
- c.在src下添加struts.xml文件,添加jar包支持:freemarker.jar ognl.jar struts2-core.jar commons-fileupload.jar
- commons-io.jar xwork-core-2.1.6.jar(这个包加上版本号,是因为下文要提到它),注意jar包支持
- 这六个包是struts必须依赖的jar包
- d.配置jsp文件,在jsp里面添加jquery支持
- e.配置action
- f ( 一)在struts2.1.6之前的版本:
- 添加相应的json包:json-lib.jar jsonplugin.jar 这里要注意很重要的一点,因为json大量引用了Apache commons的包,所以这里要一并加入,
- 需要的commons包共4个,除了commons的包外,还需要引入一个 ezmorph的包,所以这一步一共要引入7个包,列出如下:
- commons-collections.jar commons-lang.jar
- commons-beanutils.jar commons-logging.jar ezmorph.jar 再加上json的两个包共七个
- (二)struts2.1.6,添加jsonplugin0.34或者jsonplugin0.7
- (三)struts2.1.8则添加json-lib-2.2.3.jar,struts2-json-plugin,struts2-junit-plugin
- 3.插件使用:
- 1.validation插件:详见table-validation.jsp,主要为引入一个jquery.validate.js,获取相应的属性名来进行验证;
- 2.tablesort插件:目前用的是兼容中文的官网版本,一是可以实现自动排序,二是支持中文;要注意在table当中的格式,这点很重要
- 3.tablesortpager插件
- JQuery与Json结合的一些注意事项:
- 1.$.get(url,data,function(data){
- eval(data);
- })
- eval(data)将数据转换为js对象;
- 实际上如果返回的json对象,可通过将参数直接命名为json即可,如下
- $.get(url.data,function(data){},"json")
- 2.取json属性时,尽量用中括号方式,原因是如果有数字属性会发生不识别的现象
- eg:var a=obj["31001"];
- //obj.31001则可能出错
- 解决办法有其它方式:比如将属性值31001改为s31001
- 3.乱码问题:
- 在struts1.2中,通过设置表头的编码来解决乱码问题,注意对于xml和json,要分别设置为text/xml和text/json
- eg:response.setContentType("text/json; charset=utf-8");
1.struts.xml配置:
- <?xml version="1.0" encoding="UTF-8"?>
- <!-- 指定Struts 2配置文件的DTD信息 -->
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <constant name="struts.i18n.encoding" value="utf-8"></constant>
- <package name="S2SHJQuery" extends="json-default">
- <action name="show" class="action.ShowAction">
- <result type="json"/>
- </action>
- </package>
- </struts>
2.ShowAction.java配置 :
- package action;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import org.apache.struts2.json.annotations.JSON;
- import com.opensymphony.xwork2.ActionSupport;
- public class ShowAction extends ActionSupport {
- private String testvalue;
- private String result;
- private List<String> list;
- private List<User> userlist;
- private User user;
- private Map<String, User> map;
- private String[] autoarray;
- public String[] getAutoarray() {
- return autoarray;
- }
- public void setAutoarray(String[] autoarray) {
- this.autoarray = autoarray;
- }
- @JSON(serialize=false)
- public Map<String, User> getMap() {
- return map;
- }
- public void setMap(Map<String, User> map) {
- this.map = map;
- }
- @JSON(serialize=false)
- public User getUser() {
- return user;
- }
- public void setUser(User user) {
- this.user = user;
- }
- @JSON(serialize=false)
- public List<User> getUserlist() {
- return userlist;
- }
- public void setUserlist(List<User> userlist) {
- this.userlist = userlist;
- }
- @JSON(serialize=false)
- public List<String> getList() {
- return list;
- }
- public void setList(List<String> list) {
- this.list = list;
- }
- public void setTestvalue(String testvalue) {
- this.testvalue = testvalue;
- }
- @JSON(serialize=false)
- public String getTestvalue() {
- return testvalue;
- }
- @JSON(serialize=false)
- public String getResult() {
- return result;
- }
- public void setResult(String result) {
- this.result = result;
- }
- @Override
- public String execute() throws Exception {
- // TODO Auto-generated method stub
- System.out.println("test is ok: "+testvalue);
- //1.????string
- /*int i=9;
- //result=""+i+"";
- result="中国";*/
- //2.list?
- /*list=new ArrayList<String>();
- list.add("allen");
- list.add("中国");
- list.add("adc");*/
- //3.list?а?User
- /*userlist=new ArrayList<User>();
- User user1=new User();
- user1.setPassword(1);
- user1.setUsername("username1");
- User user2=new User();
- user2.setPassword(2);
- user2.setUsername("username2");
- User user3=new User();
- user3.setPassword(3);
- user3.setUsername("username3");
- userlist.add(user1);
- userlist.add(user2);
- userlist.add(user3);*/
- //4.User???????
- /*user=new User();
- user.setPassword(1);
- String username="中国";
- user.setUsername(username);
- System.out.println(user.getUsername());
- */
- //5.map????
- /*map=new HashMap<String, User>();
- User user1=new User();
- user1.setPassword(1);
- user1.setUsername("username1");
- User user2=new User();
- user2.setPassword(2);
- user2.setUsername("username2");
- User user3=new User();
- user3.setPassword(3);
- user3.setUsername("username3");
- map.put("s1",user1 );
- map.put("s2",user2 );
- map.put("s3",user3 );*/
- /*map=new HashMap<String, String>();//??????String,string???
- map.put("s1","user1");
- map.put("s2","user2");
- map.put("s3","user3");*/
- //7.直接传递数祖
- autoarray=new String[3];
- autoarray[0]="a";
- autoarray[1]="b";
- autoarray[2]="c";
- return SUCCESS;
- }
- }
3.show.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>
- <mce:script type="text/javascript" src="/S2SHJQuery/js/jquery.js" mce_src="S2SHJQuery/js/jquery.js"></mce:script>
- <base href="<%=basePath%>">
- <title>struts2+jquery+json</title>
- <mce:script type="text/javascript"><!--
- //1.struts2+jquery+json单独传递单个参数
- /*$(function(){
- $("#jquerytest").click(function(){
- var params={testvalue:$('#test').val()};
- $.ajax({
- url:"show.action",
- data:params,
- type:'post',
- dataType:'json',
- success:function(data){
- //data += decodeURI(data.shtml) ;
- alert("成功");
- alert(data.result);
- },
- error: function(){
- alert("失败");
- }
- })
- })
- })*/
- //2.jquery单独传递含单个参数的list
- /*$(function(){
- $("#jquerytest").click(function(){
- var params={testvalue:$('#test').val()};
- $.ajax({
- url:"show.action",
- data:params,
- type:'post',
- dataType:'json',
- success:function(data){
- var jsonobject=data.list;
- for(var j=0;j<jsonobject.length;j++)
- {
- alert(jsonobject[j]);
- }
- },
- error: function(){
- alert("失败");
- }
- })
- })
- })*/
- //3.jquery单独传递含对象类型User的list
- $(function(){
- $("#jquerytest").click(function(){
- var params={testvalue:$('#test').val()};
- $.ajax({
- url:"show.action",
- data:params,
- type:'post',
- dataType:'json',
- success:function(data){
- var jsonobject=data.userlist;
- /*for(var j=0;j<jsonobject.length;j++)
- {
- alert(jsonobject[j].username);
- alert(jsonobject[j].password);
- }
- */
- $.each(jsonobject,function(key,value){
- alert(key+" "+value.username);
- alert(key+" "+value.password);
- })
- }
- ,
- error: function(){
- alert("失败");
- }
- })
- })
- })
- //4.jquery单独传递User对象类型
- /*$(function(){
- $("#jquerytest").click(function(){
- var params={testvalue:$('#test').val()};
- $.ajax({
- url:"show.action",
- data:params,
- type:'post',
- dataType:'json',
- contentType: "application/x-www-form-urlencoded; charset=UTF-8",
- success:function(data){
- var jsonobject=data.user;
- alert(jsonobject.username);
- },
- error: function(){
- alert("失败");
- }
- })
- })
- })*/
- //5.jquery传递含User对象类型的map类型
- /*$(function(){
- $("#jquerytest").click(function(){
- var params={testvalue:$('#test').val()};
- $.ajax({
- url:"show.action",
- data:params,
- type:'post',
- dataType:'json',
- success:function(data){
- var jsonobject=data.map;
- alert(data.map.s1.username);//一步一步获取值
- $.each(data.map,function(key,value){
- alert(key+": "+value.username);
- })
- },
- error: function(){
- alert("失败");
- }
- })
- })
- })*/
- // --></mce:script>
- </head>
- <body>
- <form>
- <input type="button" value="JQuery" id="jquerytest"><br>
- <input type="text" value="美国" name="test" id="test">
- </form>
- </body>
- </html>
4.tableopen.jsp弹出层插件:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>Thickbox Plus - Download by http://www.codefans.net</title>
- <mce:style type="text/css" media="all"><!--
- @import "css/global.css";
- --></mce:style><style type="text/css" media="all" mce_bogus="1">@import "css/global.css";</style>
- <mce:script src="/S2SHJQuery/js/jquery.js" mce_src="S2SHJQuery/js/jquery.js" type="text/javascript"></mce:script>
- <mce:script src="/S2SHJQuery/lib/thickbox_plus.js" mce_src="S2SHJQuery/lib/thickbox_plus.js" type="text/javascript"></mce:script>
- </head>
- <body>
- <div id="contentPad">
- <h1>Thickbox Plus</h1>
- <div>
- <a href="images/image1.jpg" mce_href="images/image1.jpg" title="Sample caption" class="thickbox"><img src="images/image1_t.jpg" mce_src="images/image1_t.jpg" alt="Image 1" /></a>
- <a href="images/image2.jpg" mce_href="images/image2.jpg" title="Another sample caption" class="thickbox"><img src="images/image2_t.jpg" mce_src="images/image2_t.jpg" alt="Image 2"/></a>
- </div>
- </div>
- </body>
- </html>
5.tablesorter.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>列表排序</title>
- <link rel="stylesheet" type="text/css" media="screen"
- href="css/screen.css" />
- <mce:script src="/S2SHJQuery/js/jquery.js" mce_src="S2SHJQuery/js/jquery.js"
- type="text/javascript"></mce:script>
- <mce:script
- src="/S2SHJQuery/lib/jquery.tablesorter.js"
- type="text/javascript"></mce:script>
- <mce:script type="text/javascript"><!--
- $(document).ready(function() {
- $("#userList").tablesorter({sortList: [ [2,1]]} );//也可通过传递参数来实现
- });
- // --></mce:script>
- </head>
- <body>
- This is my JSP page.
- <br>
- <table id="userList">
- <thead>
- <tr>
- <th>Name</th>
- <th>Sex</th>
- <th>old</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>李四</td>
- <td>男</td>
- <td>14</td>
- </tr>
- <tr>
- <td>张三</td>
- <td>男</td>
- <td>50</td>
- </tr>
- <tr>
- <td>赵五</td>
- <td>Sex</td>
- <td>60</td>
- </tr>
- <tr>
- <td>丽丽</td>
- <td>女</td>
- <td>18</td>
- </tr>
- <tr>
- <td>蝈蝈</td>
- <td>女</td>
- <td>24</td>
- </tr>
- </tbody>
- </table>
- </body>
- </html>
6.tablesortpager.jsp排序兼分页插件:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <mce:script language="javascript" type="text/javascript" src="/S2SHJQuery/lib/jquery-1.2.6.pack.js" mce_src="S2SHJQuery/lib/jquery-1.2.6.pack.js"></mce:script>
- <mce:script language="javascript" type="text/javascript" src="/S2SHJQuery/lib/jquery.tablesorter.js" mce_src="S2SHJQuery/lib/jquery.tablesorter.js"></mce:script>
- <mce:script language="javascript" type="text/javascript" src="/S2SHJQuery/lib/jquery.tablesorter.pager.js" mce_src="S2SHJQuery/lib/jquery.tablesorter.pager.js"></mce:script>
- <mce:script language="javascript"><!--
- $(document).ready(function(){
- $("#userList").tablesorter({sortList: [ [2,1]]}).tablesorterPager({container: $("#pager")});
- });
- // --></mce:script>
- <title>jquery.tablesorter实现table排序(含分页)</title>
- </head>
- <body>
- <table width="50%" border="1" align="center" cellpadding="0" cellspacing="0" id="userList">
- <thead>
- <tr class="main-font2">
- <th>Name</th>
- <th>Sex</th>
- <th>old</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>李四</td>
- <td>男</td>
- <td>14</td>
- </tr>
- <tr>
- <td>张三</td>
- <td>男</td>
- <td>50</td>
- </tr>
- <tr>
- <td>赵五</td>
- <td>Sex</td>
- <td>60</td>
- </tr>
- <tr>
- <td>丽丽</td>
- <td>女</td>
- <td>18</td>
- </tr>
- <tr>
- <td>蝈蝈</td>
- <td>女</td>
- <td>24</td>
- </tr>
- <tr>
- <td>飞行1</td>
- <td>女</td>
- <td>24</td>
- </tr>
- <tr>
- <td>飞行2</td>
- <td>女</td>
- <td>24</td>
- </tr>
- <tr>
- <td>飞行3</td>
- <td>女</td>
- <td>24</td>
- </tr>
- <tr>
- <td>飞行4</td>
- <td>女</td>
- <td>24</td>
- </tr>
- <tr>
- <td>飞行5</td>
- <td>女</td>
- <td>24</td>
- </tr>
- <tr>
- <td>飞行6</td>
- <td>女</td>
- <td>24</td>
- </tr>
- <tr>
- <td>飞行7</td>
- <td>女</td>
- <td>24</td>
- </tr>
- </tbody>
- </table>
- <div id="pager" class="pager">
- <form align="center">
- 每页记录数:
- <select class="pagesize">
- <option selected="selected" value="10">10</option>
- <option value="15">15</option>
- <option value="20">20</option>
- </select>
- <input type="hidden" class="pagedisplay"/>
- <a href="#" mce_href="#" class="first" title="首页">首页</a> |
- <a href="#" mce_href="#" class="prev" title="上一页">上一页</a> |
- <a href="#" mce_href="#" class="next" title="下一页">下一页</a> |
- <a href="#" mce_href="#" class="last" title="尾页">尾页</a> |
- 共<span class="totalpage"></span>页 |
- 第<span class="curpage"></span>页 |
- 到第 <input name="pageNo" type="text" class="pageNo txt" size="3" value=""/> 页 <a href="#" mce_href="#" class="pageGo">GO</a>
- </form>
- </div>
- </body>
- </html>
7.tablesuggest.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>搜索框提示</title>
- <link rel="stylesheet" type="text/css" media="jquery.autocomplete.css"
- href="css/jquery.autocomplete.css" />
- <mce:script src="/S2SHJQuery/js/jquery.js" mce_src="S2SHJQuery/js/jquery.js"
- type="text/javascript"></mce:script>
- <mce:script
- src="/S2SHJQuery/lib/jquery.autocomplete.js"
- type="text/javascript"></mce:script>
- <mce:script type="text/javascript"><!--
- var arr = ["Allen","Albert","Alberto","Alladin"];
- $(document).ready(function() {
- //$("#userList").autocomplete(arr);
- $("#userList").autocomplete("show.action", { selectFirst:true,extraParams: {testvalue:function(){return $('#userList').val();}},
- width: 170,minChars:1, selectOnly: 1,inputSeparator:':'});
- });
- // --></mce:script>
- </head>
- <body>
- This is my JSP page.
- <br>
- <table >
- <tbody>
- <tr>
- <td>提示框测试:<input type="text" name="userList" id="userList"/></td>
- </tr>
- </tbody>
- </table>
- </body>
- </html>
8.table-validation.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>
- <link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" mce_href="css/screen.css" />
- <mce:script src="/S2SHJQuery/js/jquery.js" mce_src="S2SHJQuery/js/jquery.js" type="text/javascript"></mce:script>
- <mce:script src="/S2SHJQuery/lib/jquery.validate.js" mce_src="S2SHJQuery/lib/jquery.validate.js" type="text/javascript"></mce:script>
- <mce:script src="/S2SHJQuery/lib/jquery.validate.messages_cn.js" mce_src="S2SHJQuery/lib/jquery.validate.messages_cn.js" type="text/javascript"></mce:script>
- <mce:style type="text/css"><!--
- * { font-family: Verdana; font-size: 96%; }
- label { width: 10em; float: left; }
- label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
- p { clear: both; }
- .submit { margin-left: 12em; }
- em { font-weight: bold; padding-right: 1em; vertical-align: top; }
- --></mce:style><style type="text/css" mce_bogus="1">* { font-family: Verdana; font-size: 96%; }
- label { width: 10em; float: left; }
- label.error { float: none; color: red; padding-left: .5em; vertical-align: top; }
- p { clear: both; }
- .submit { margin-left: 12em; }
- em { font-weight: bold; padding-right: 1em; vertical-align: top; }</style>
- <mce:script type="text/javascript"><!--
- $(document).ready(function(){
- //引入验证的js.jquery.validate.js,并引入中文js jquery.validate.messages_cn.js
- //可在js里面进行修改,注意css格式
- //获取form值后,即可根据id值来进行validation操作
- //取相应的验证规则:对应的输入值即可
- //可参照锋利的JQuery P218页
- //同时可利用这一特性生成验证码
- $("#commentForm").validate({
- rules: {
- username: {
- required: true,
- minlength: 3
- },
- email: {
- required: true,
- email: true
- },
- url:"url",
- comment: "required"
- }
- });
- });
- // --></mce:script>
- </head>
- <body>
- <form class="cmxform" id="commentForm" method="get" action="">
- <fieldset>
- <legend>jquery-validation 插件jsp</legend>
- <p>
- <label for="cusername">用户名:</label>
- <em>*</em><input id="cusername" name="username" size="25" />
- </p>
- <p>
- <label for="cemail">邮件:</label>
- <em>*</em><input id="cemail" name="email" size="25" />
- </p>
- <p>
- <label for="curl">URL:</label>
- <em> </em><input id="curl" name="url" size="25" value="" />
- </p>
- <p>
- <label for="ccomment">评论:</label>
- <em>*</em><textarea id="ccomment" name="comment" cols="22">