exclude properties in json result

引用struts-json-plugin.XX.xx.jar。引入它里面的json-plugin.xml,然后user的package要继承json-default。引入json interceptor,如下:
 <interceptors>
			<interceptor-stack name="ecsStack">
				<interceptor-ref name="defaultStack">
					<param name="exception.logEnabled">true</param>
					<param name="exception.logLevel">ERROR</param>
				</interceptor-ref>
				<interceptor-ref name="json"><param name="contentType">application/json;charset=utf-8</param></interceptor-ref>
			</interceptor-stack>
        </interceptors>

如果去看下JSONInterceptor源码,发现有noCache和excludeNullProperties属性,但是在这里设置这两个参数无效。
如果想对json result设置这两个参数可以在json result type里设置:
<result-types>
    		<result-type name="json" class="org.apache.struts2.json.JSONResult">
    			<param name="noCache">true</param>
    			<param name="excludeNullProperties">true</param>
    		</result-type>
    	</result-types>

在json result序列化数据的时候,可能有些数据不需要序列化,可以在result里配置:
<result name="browse" type="json"><param name="excludeProperties">seriesSet</param><param name="root">category</param></result>

<result name="search_ajax" type="json"><param name="excludeProperties">\[\d+\]\.seriesSet</param><param name="root">categoryList</param></result>

其中seriesSet是category对象中的一个Set属性,注意在过滤整个categoryList里的seriesSet配置方式。

补充:关于最后excludeProperties的设置,当时我在hibernate中配置one-to-many lazy loading=true, 但是console中打印出来的sql表明并不是lazy load,而且前台也能看到那些“懒加载”数据,后来跟踪下代码,DAO层查询的时候,“懒数据”并没有查询出来,然而在json 序列化数据的时候,会把那些“懒数据”也序列化出来,所以console中跑了大量的sql。如果前台不需要这些数据,一定要设置excludeProperties,提升性能。

参考资料:http://struts.apache.org/release/2.1.x/docs/json-plugin.html

你可能感兴趣的:(json,struts2)