首先看下面的配置文件中的两种写法:固然Action所在的包必须继承json-default:
<package name="default" extends ="json-default" >html
第一种:java
<action name="upload_*" class="uploadAction" method="{1}"> <result type="json"> <param name="root">fileName</param> </result> </action>
第二种:android
<action name="uploadJson" class="uploadJsonAction" method="upload"> <result type="json" name="success"></result> </action>
固然,两种方式都能达到相应的效果,可是开发中咱们建议使用第一种;正则表达式
可是,strut2的开发者显然作的比较得当,下面的注解方式能够帮你改进很多你的代码,固然我的以为仍是加上root方便、简单:json
下面看看其余几种配置的写法:测试
第三种:excludeNullProperties 参数:表示是否去掉空值, 默认值是false,若是设置为true会自动将为空的值过滤,只输出不为空的值。google
<result type="json"> <param name="excludeNullProperties">true</param> </result>
第四种: ignoreHierarchy 参数:表示是否忽略等级,也就是继承关系,好比:TestAction继承于BaseAction,那么TestAction中返回的json字符串默认是不会包含父类BaseAction的 属性值,ignoreHierarchy值默认为true,设置为false后会将父类和子类的属性一块儿返回。spa
<result type="json"> <param name="ignoreHierarchy">false</param> </result>
第五种: includeProperties 参数:输出结果中须要包含的属性值(若是属性是对象的引用,若要json化引用的全部属性,则使用person.*),这里正则表达式和属性名匹配,能够用“,”分割填充多个正则表达式。code
<result type="json"> <param name="includeProperties">person.*, person\.name</param> </result>
第六种:excludeProperties 参数:输出结果须要剔除的属性值,也支持正则表达式匹配属性名,能够用“,”分割填充多个正则表达式,orm
<result type="json"> <param name="excludeProperties ">person.*, person\.name</param> </result>
下面讲讲几种特殊的状况:
action 代码:
public class TestingAction extends ActionSupport { private static final long serialVersionUID = 1L; private static Log log = LogFactory.getLog(TestingAction.class); private String resultStr = "success";//判断自测是否成功 private Integer testHeadId;// 试卷id private String testLineId;// 试题id private String userId;// 登陆用户的id private String testResult;// 测试结果 google gson拼凑的结果集 private TestLine testLine;//该道题目的相关信息 public List<ITestLine> testLines;//android端返回的json
Bean:
public class TestLine implements java.io.Serializable { // Fields private String testLineId; private TestHead testHead; private Integer type; private Integer sortIndex; private Integer score; private String tigan; private String tizhi; private String jiexi; private String daan; private Timestamp lastUpdateTime; private String lastUpdateBy;
上面你们看到,action中有一个对象的引用testLine;而testLine实体中又包含另外一个对象TestHead的引用;其余的我就不说了,若是你也碰到这种状况,实体嵌套,那么使用struts2的json序列化时,默认会帮你序列化这个bean(testLine)中全部的属性,属性中若是涉及其余实体引用时,会继续帮你序列化该引用(TestHead)的属性值,就这样,你有多少层的嵌套,struts2就会帮你序列化多少层,这是你想要的结果吗?
处理这种问题的方法是:咱们只须要告诉struts2我须要序列化那些属性:咱们拿到通过Hibernate处理的以后的结果oldTestLine以后,须要从新建立咱们须要序列化的对象:
TestLine testLine = new TestLine();
而后将须要的字段set值便可;
testLine .set(oldTestLine.get*);
处理须要序列化的集合(list、 map)问题(List<ITestLine> testLines)也是同解;
至于比较不错的json架包,我的推荐google gson。
推荐篇使用struts2返回各类类型的文章:http://www.open-open.com/lib/view/open1325518231062.html