net.sf.json中修改和過濾已生成的json資料的簡單講解
阿新 • • 發佈:2019-01-11
// 查詢所有父類板塊 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"; }