日期:2014-05-16  浏览次数:20429 次

Struts2返回JSON
1.导入jsonplugin包

Struts2.16:导入jsonplugin-0.34.jar包(下载包)和commons-logging-1.0.4.jar(Struts2 lib下有)

Struts2.18导入struts2-json-plugin-2.1.8.1.jar(Struts2 lib下有)
2.struts.xml中package 中extends="json-default"

<package name="json" namespace="/json" extends="json-default">

3.result 中type="json"

<!-- 封装所以的get开头的方法 -->
<result type="json" name="user">
</result>

<!-- 只包含user.id属性 -->
<result type="json" name="user">
    <param name="includeProperties">              
        user\.id
    </param>
</result>

<!-- 不包含user属性 -->
<result type="json" name="list">
    <param name="excludeProperties">              
        user
    </param>
</result>

<!-- 根对象只包含user -->
<result type="json"> 
    <param name="root"> 
        user
    </param> 
</result>

<!-- "root"对象中父类的field(属性)不会(会?) 默认存放到 JSON数据中,如果不想这样做,需要在配置时指定 ignoreHierarchy 为 false:  -->
<result type="json"> 
    <param name="ignoreHierarchy">false</param> 
</result>

4.避免使用get开头的action方法

在属性get方法上面加
@JSON(name="newName")json中的名称
@JSON(serialize=false) 属性不被加入json
@JSON(format="yyyy-MM-dd") 格式化日期

5.在action中赋值,返回对应的result字符串


转换成json时发生的错误:

No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: ***************_$$_javassist_15["hibernateLazyInitializer"])
后来google发现在je上有人有类似的问题:http://147175882.iteye.com/blog/380823

147175882 写道
分析原因,是因为jsonplugin用的是java的内审机制.hibernate会给被管理的pojo加入一个hibernateLazyInitializer属性,jsonplugin会把hibernateLazyInitializer也拿出来操作,并读取里面一个不能被反射操作的属性就产生了这个异常.


不过我用的是jackson来转json,所以想到了用annotation来排除hibernateLazyInitializer 这个属性
在你的pojo类声明加上:

Java代码
@JsonIgnoreProperties(value={"hibernateLazyInitializer"}) 

或者:


这个错其实很易明了,因为你序列化对象A时,需要把里面的多对一关系的B拿出来,而B里面又有A的集合,如此反复,便报这样的错了,解决这个问题的方法在于在 多对一关系中的的一方的set 集体的get 方法前面添加@JsonIgnore即可,如:
Java代码
@JsonIgnore public Set getStuedntses() { 
        return studentses; 
    } 

添加这个注解后,无论你是lazy="true" or lazy="false"他都不会去序列化你的了!



positioned update not supported异常解决

该异常有两种解决方法:
第一:在struts.xml文件的配置中排除不要被JSON序列化的属性,例如:
Java代码
<action name="functions" class="getFunctionsAction" method="functions_getList"> 
            <result type="json"> 
             <param name="excludeProperties">functionsService</param> 
            </result> 
        </action> 

其中functionsService就是不要被JSON序列化的属性。
第二:在Action文件中去除不要被JSON序列化的属性的get()方法,例如:
Java代码
public IFunctionsService getFunctionsService() {&nbs