public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ LibtypeDAO libtypeDAO = new LibtypeDAO(); List<Libtype> list = libtypeDAO.findAll(); JSONArray jsonArray = JSONArray.fromObject(list); return null; }原因很简单,在Libtype中, 有一个与List无关的属性值,即libs,我们只需要ltid和ltype,所以报错。
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ LibtypeDAO libtypeDAO = new LibtypeDAO(); List<Libtype> list = libtypeDAO.findAll(); JsonConfig jsonConfig = new JsonConfig(); //建立配置文件 jsonConfig.setIgnoreDefaultExcludes(false); //设置默认忽略 jsonConfig.setExcludes(new String[]{"libs"}); //此处是亮点,只要将所需忽略字段加到数组中即可,在上述案例中,所要忽略的是“libs”,那么将其添到数组中即可,在实际测试中,我发现在所返回数组中,存在大量无用属性,如“multipartRequestHandler”,“servletWrapper”,那么也可以将这两个加到忽略数组中. JSONArray jsonArray = JSONArray.fromObject(list,jsonConfig); //加载配置文件 return null; }
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ LibtypeDAO libtypeDAO = new LibtypeDAO(); List<Libtype> list = libtypeDAO.findAll(); JsonConfig jsonConfig = new JsonConfig(); //建立配置文件 jsonConfig.setIgnoreDefaultExcludes(false); //设置默认忽略 jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); //此处是亮点,不过经过测试,第2种方法有些悲剧,虽然可以使用,但其结果貌似循环数次,至于为啥,还请高人指点。 JSONArray jsonArray = JSONArray.fromObject(list,jsonConfig); //加载配置文件 return null; }
JavaBean:
public LibtypeForm{ int ltid; string ltname; } public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ LibtypeDAO libtypeDAO = new LibtypeDAO(); List<Libtype> list = libtypeDAO.findAll(); List<LibtypeForm> formList = new ArrayList(); for(Libtype libtype : list){ LibtypeForm form = new LibtypeForm(); form.setLtid(libtype .getLtid); form.setLtname(libtype.getLtname); formList.add(form); } JSONArray jsonArray = JSONArray.fromObject(formList); return null; }