將List轉換為Json物件
阿新 • • 發佈:2018-12-16
將List轉換為Json物件,分別有兩個Json的jar包:
1、org.json.JSONArray包
2、net.sf.json.JSONArray包
兩個JSONArray分別實現方式:
1、org.json.JSONArray包
List al = articleMng.find(f); System.out.println(al.size()); HttpServletResponse hsr = ServletActionContext.getResponse(); if(null == al){ return ; } for(Article a : al){ System.out.println(a.getId()+a.getDescription()+a.getTitle()); } JSONArray json = new JSONArray(); for(Article a : al){ JSONObject jo = new JSONObject(); jo.put("id", a.getId()); jo.put("title", a.getTitle()); jo.put("desc", a.getDescription()); json.put(jo); } try { System.out.println(json.toString()); hsr.setCharacterEncoding("UTF-8"); hsr.getWriter().write(json.toString()); } catch (IOException e) { e.printStackTrace(); }
2、net.sf.json.JSONArray包 此包下Json物件大多數以JSONArray.fromObject()方法來完成。
個人推薦使用 net.sf.json.JSONArray jar包來完成Json的轉換。