1. 返回数据形式
Class returnMsg{
boolean success;
String msg;
String errorMsg;
}
2.问题
当msg中的数据由对象 或 集合转换而来时, 用JSONObject.fromObject(obj).toString()返回后带有'\'
3. 解决方案
将集合类型数据转换成jsonArray,用Map来存放数据,返回map
userList = accountManager.findDeptUser(deptId); JsonConfig jsonConfig = new JsonConfig();jsonConfig.setExcludes(new String[]{ "role"});// 排除某些字段jsonConfig.setIgnoreDefaultExcludes(true);jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); JSONArray jsonArray = JSONArray.fromObject(userList, jsonConfig); MapresultMap = new HashMap (); resultMap.put("success", true); resultMap.put("msg", jsonArray); resultMap.put("errmsg", ""); response.setHeader("Cache-Control", "no-cache"); response.setContentType("text/json; charset=UTF-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = null; try { out = response.getWriter(); out.print(JSONArray.fromObject(resultMap)); out.flush(); } catch (Exception e) { }finally{ if(out!=null){ out.close(); } }
以上代码实现排除牟些字段, 也可以指定某些字段
ListcataTempList = cataTemp.find(); JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setJsonPropertyFilter(new PropertyFilter(){ @Override public boolean apply(Object arg0, String name, Object value) { if(name.equals("id") || name.equals("name")){ return false; }else{ return true; } }}); jsonConfig.setIgnoreDefaultExcludes(true); jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); JSONArray jsonArray = JSONArray.fromObject(cataTempList, jsonConfig); resultMap.put("success", true); resultMap.put("msg", jsonArray); resultMap.put("errmsg", "");