導入第三方jar包:java
》commons-beanutils-1.7.0.jarjson
》commons-collections-3.1.jar工具
》commons-lang-2.5.jarspa
》commons-logging-1.1.1.jarcode
》ezmorph-1.0.3.jarblog
》json-lib-2.1-jdk15.jar ci
(1)JavaBean->JSONstring
》JSONArray jsonArray = JSONArray.fromObject(city);it
》String jsonJAVA = jsonArray.toString();io
(2)List<JavaBean>->JSON
》JSONArray jsonArray = JSONArray.fromObject(cityList);
》String jsonJAVA = jsonArray.toString();
(3)List<String>->JSON
》JSONArray jsonArray = JSONArray.fromObject(stringList);
》String jsonJAVA = jsonArray.toString();
(4)Map<String,Object>->JSON【重點】
package loaderman.bean2json; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import org.junit.Test; /** * 演示用第三方工具類,將JavaBean、List、Map<String,Object>轉成JSON文本 **/ public class TestJson { @Test public void javabean2json() { User user = new User(1, "哈哈", 123, "男"); JSONArray jsonArray = JSONArray.fromObject(user); String jsonJAVA = jsonArray.toString(); System.out.println(jsonJAVA); //[{"id":1,"name":"哈哈","sal":7000}] } @Test public void list2json() { List<User> userList = new ArrayList<User>(); userList.add(new User(1, "恩和", 123, "男")); userList.add(new User(2, "恩和老婆", 123, "男")); userList.add(new User(3, "恩和小孩", 24, "男")); JSONArray jsonArray = JSONArray.fromObject(userList); String jsonJAVA = jsonArray.toString(); System.out.println(jsonJAVA); //[{"id":1,"name":"恩和","sal":7000},{"id":2,"name":"福老婆","sal":8000},{"id":3,"name":"恩和","sal":20000}] } @Test public void map2json() { List<User> userList = new ArrayList<User>(); userList.add(new User(1, "張三", 7000, "男")); userList.add(new User(2, "張三老婆", 8000, "女")); userList.add(new User(3, "張三小孩", 20000, "男")); userList.add(new User(4, "張三小孩的小孩", 40000, "男")); Map<String, Object> map = new HashMap<String, Object>(); //total表示集合的長度 map.put("total", userList.size()); //rows表示集合內容 map.put("rows", userList); JSONArray jsonArray = JSONArray.fromObject(map); String jsonJAVA = jsonArray.toString(); System.out.println(jsonJAVA); jsonJAVA = jsonJAVA.substring(1, jsonJAVA.length() - 1); System.out.println(jsonJAVA); } }