net.sf.json中修改和过滤已生成的json数据的简单讲解
发布时间:2020-12-16 19:18:01 所属栏目:百科 来源:网络整理
导读:// 查询所有父类板块public String findAllFatherBoard() throws IOException {// 接收查询的结果集ListForumBoard boardList = boardDAO.get("from ForumBoard fb where fb.forumBoard=null and fb.boardAuditing='true'");// 判断是否存在数据if (boardLis
// 查询所有父类板块 public String findAllFatherBoard() throws IOException { // 接收查询的结果集 List<ForumBoard> boardList = boardDAO .get("from ForumBoard fb where fb.forumBoard=null and fb.boardAuditing='true'"); // 判断是否存在数据 if (boardList != null && boardList.size() > 0) { // 声明JsonConfig配置文件对象 JsonConfig jsonConfig = new JsonConfig(); // 设置循环检测策略 jsonConfig .setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); // json字段重命名 // java--->json修改字段名字的时候使用jsonConfig.registerJsonPropertyNameProcessor(target,// propertyNameProcessor); // json--->java的时候使用jsonConfig.registerJavaPropertyNameProcessor(target,// propertyNameProcessor); jsonConfig.registerJsonPropertyNameProcessor(ForumBoard.class,// 创建内部类修改字段名字的一个接口 new PropertyNameProcessor() { @Override public String processPropertyName(Class obj,String name) { // 将javaben中的指定字段修改名字,if (name.equalsIgnoreCase("boardId")) { return "id"; } else if (name.equalsIgnoreCase("boardCountPt")) { return "countPost"; } else if (name.equalsIgnoreCase("boardTitle")) { return "text"; } else if (name.equalsIgnoreCase("forumBoards")) { return "children"; } else if (name.equalsIgnoreCase("boardSeeNb")) { return "countSee"; } else if (name.equalsIgnoreCase("forumBoard")) { return "fatherBoard"; } // System.out.println("==========" + name); return "other"; } }); // 设置json的属性的过滤器 // 创建属性过滤器的内部内部对象 jsonConfig.setJsonPropertyFilter(new PropertyFilter() { // 重写内部的允许字段通过的方法 public boolean apply(Object source,String name,Object value) { // 排除的字段名字(属性名) if (name.equals("forumPosts") || name.equals("forumUser") || name.equals("id") || name.equals("boardCreatTm") || name.equals("boardAuditing")) { return true; } else { return false; } } }); // jsonConfig.setRootClass(ForumBoard.class); // 将对象转换成json数据 // 创建jsonArray数组的jso对象,并读取配置对象 try { // 将目标对象和json配置对象一起读入JSONArray.fromObject(boardList,// jsonConfig); // 这样就可以获取想要的数据的json格式的数据了 JSONArray jsonArray = JSONArray.fromObject(boardList,jsonConfig); System.out.print(jsonArray.toString()); // 存入域中 HttpServletResponse response = ServletActionContext .getResponse(); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.println(jsonArray.toString()); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } } else { message = "NOFIND"; } return "FINDALLBOARD"; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |