SSH中使用Gson将List封装成Json返回
在数据处理时,有时候需要将一个List集合封装成JSON返回。但如果使用的是SSH框架,一直出现很纠结的问题;Hibernater的ORM属性,将自动映射Set数据。
在SSH中,如果数据处理时,Bean的属性中含有Set集合,此数据不为空时,将返回
Messages: | |
File: | com/google/gson/stream/JsonWriter.java |
Line number: | 580 |
Stacktraces
java.lang.reflect.InvocationTargetException
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:446) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:285) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
的相关错误。多次测试后,目前的解决方案主要是将Bean的Set集合设置为NULL,或另外写一个VO,不含有Set属性的。
温馨提示:此方法仅对GSON有效,org.json目前无法处理(相当相当纠结,浪费了好多时间也没能解决,如果哪位大虾已经解决的,麻烦指导一下。)
public String allZone() throws Exception{ list = zoneServiceImpl.getAllZone(); //方案一:使用VO,新的属性里不含Set集合 for(int i = 0 ;i<list.size();i++){ ZoneVO zone = new ZoneVO(); zone.setZoneId(list.get(i).getZoneId()); zone.setZoneName(list.get(i).getZoneName()); listVO.add(zone); } //方案二:新所有的Set集合设置为空 for(int i = 0 ;i<list.size();i++){ list.get(i).setAreas(null); } Gson gson = new Gson(); HttpServletResponse response=ServletActionContext.getResponse(); response.setContentType("application/json;charset=UTF-8"); PrintWriter out = response.getWriter(); out.print(gson.toJson(list)); out.print(gson.toJson(listVO)); out.flush(); out.close(); return "null"; }
返回的结果:
[{"zoneId":1,"zoneName":"福田区"},{"zoneId":2,"zoneName":"罗湖区"},{"zoneId":3,"zoneName":"南山区"},{"zoneId":4,"zoneName":"盐田区"},{"zoneId":5,"zoneName":"宝安区"},{"zoneId":6,"zoneName":"龙华区"},{"zoneId":7,"zoneName":"光明区"},{"zoneId":8,"zoneName":"龙岗区"},{"zoneId":9,"zoneName":"坪山区"},{"zoneId":10,"zoneName":"大鹏区"}]
[{"zoneId":1,"zoneName":"福田区"},{"zoneId":2,"zoneName":"罗湖区"},{"zoneId":3,"zoneName":"南山区"},{"zoneId":4,"zoneName":"盐田区"},{"zoneId":5,"zoneName":"宝安区"},{"zoneId":6,"zoneName":"龙华区"},{"zoneId":7,"zoneName":"光明区"},{"zoneId":8,"zoneName":"龙岗区"},{"zoneId":9,"zoneName":"坪山区"},{"zoneId":10,"zoneName":"大鹏区"}]