所需要的包
commons-httpclient-3.1.jar
commons-lang-2.4.jar
commons-logging-1.1.1.jar
json-lib-2.4-jdk15.jar
ezmorph-1.0.6.jar
commons-collections-3.2.1.jar
1、bean转为Json
User u = new User();
u.setAge(22);
u.setUsername("hzucmj");
u.setEnabled(true);
JSONObject json = JSONObject.fromObject(u);
System.out.println(json.toString()); //结果为:{"enabled":true,"username":"hzucmj","age":22}
2、List转为Json
User u1 = new User();
u1.setAge(22);
u1.setUsername("hzucmj");
u1.setEnabled(true);
User u2 = new User();
u2.setAge(20);
u2.setUsername("ctf");
u2.setEnabled(true);
List<Object> list = new ArrayList<Object>();
list.add(u1);</p>
list.add(u2);</p>
JSONArray json = JSONArray.fromObject(list);
System.out.println(json.toString()); //结果为:[{"enabled":false,"username":"ctf","age":20},{"enabled":false,"username":"","age":0}]
3、Map转为Json
HashMap<String, Comparable> map = new HashMap<String, Comparable>();
map.put("name", "hzucmj");
map.put("age", 22);
JSONObject json = JSONObject.fromObject(map);
System.out.println(json.toString()); //结果为:{"name":"hzucmj","age":22}