JSONArray和JSONObject的詳細使用:http://blog.csdn.net/yangbobo1992/article/details/8350765
/** * ajax調用返回json數組 * @param list */ public void printList(List<?> list){ HttpServletResponse response = ServletActionContext.getResponse(); //獲取response實例 response.setContentType("text/html"); //設置輸出類型 response.setCharacterEncoding("UTF-8"); //設置輸出編碼 /*JsonConfigFactory.getInstance(); JSONArray jsonArray = new JSONArray(); jsonArray.addAll(list, JsonConfigFactory.getInstance()); */ try { response.getWriter().print(JSONArray.fromObject(list, JsonConfigFactory.getInstance())); } catch (IOException e) { e.printStackTrace(); } } /** * ajax調用返回json對象 * @param obj */ public void printObject(Object obj){ HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); try { response.getWriter().print(JSONObject.fromObject(obj,JsonConfigFactory.getInstance())); } catch (IOException e) { e.printStackTrace(); } } /** * ajax調用返回json對象 * @param obj */ public void printSting(String str){ HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); try { response.getWriter().print(str); } catch (IOException e) { e.printStackTrace(); }
