将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的转换。