struts2与json

来源:互联网 发布:钟表行业数据 编辑:程序博客网 时间:2024/06/10 18:18

struts核心包:


json需要的包:


commons-logging-*.jar在导入struts核心包的时候就导入了,所以导入json包的时候可以去掉这个包

Struts2中action的代码:




其中JSONObeject用于储存Map集合和bean,数组、list、用JSONArray储存。格式如下:

JSONObject:

JSONObject jsonObject =JSONObject.fromObject(object);//将object转化为json对象

JSONArray:

JSONArray jsonArray =JSONArray.fromObject(object);//将object转化为json对象

 

获得json对象后,我们得将json对象转换为字符串返回给前台,使用toString()方法。

在这个action中返回的是result,且必须保证在这个action类中有action的getter方法。

在这段代码之中还有一段代码:// 先过滤对set集合的拆解

                   JsonConfigconfig = new JsonConfig();

                   config.setJsonPropertyFilter(newPropertyFilter() {

                            @Override

                            publicboolean apply(Object arg0, String arg1, Object arg2) {

                                     if(arg1.equals("students") || arg1.equals("college") ||arg1.equals("classGrade")

                                                        ||arg1.equals("teacher") || arg1.equals("departments")) {

                                               returntrue;

                                     }else {

                                               returnfalse;

                                     }

                            }

                   });

这段代码是对json中所传输对象有关,因为我传输的对象是一个list集合,且这个集合的实体类包含与其他实体类的关联关系(ManyToOne、OneToMany).如果不加上这段代码对会出现死循环net.sf.json.JSONException: There is a cycle in the hierarchy!通过这个方法过滤掉List里的相应属性,只要让它返回true就可过滤掉关联对象。这样不会一直读取关联对象的属性。

接下来是配置struts.xml配置文件。



还有得注意的是,package包下的externds要继承”json-default”,extends="struts-default”