net.sf.json中修改和過濾已生成的json數據的簡單講解

// 查詢所有父類板塊
	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";
	}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章