前面咱們在使用Strus2的時候,Struts2自帶了組件可以讓JavaBean對象、集合轉成是JSON,不用咱們本身拼接…這是很是方便的。可是,咱們不必定使用Struts2框架來作開發呀。所以,咱們還得學習使用第三方庫來將JavaBean對象、集合轉成JSONjavascript
導入開發包package cn.itcast.javaee.js.bean2json; import net.sf.json.JSONArray; import java.util.*; /** * 使用第三方工具,將JavaBean對象/List或Set或Map對象轉成JSON * @author AdminTC */ public class TestBean2Json { private static void javabean2json() { City city = new City(1,"廣州"); JSONArray jSONArray = JSONArray.fromObject(city); String jsonJAVA = jSONArray.toString(); System.out.println(jsonJAVA); //[{"id":1,"name":"廣州"}] } private static void list2json() { List<City> cityList = new ArrayList<City>(); cityList.add(new City(1,"廣州")); cityList.add(new City(2,"珠海")); JSONArray jSONArray = JSONArray.fromObject(cityList); String jsonJAVA = jSONArray.toString(); System.out.println(jsonJAVA); //[{"id":1,"name":"廣州"},{"id":2,"name":"珠海"}] } private static void set2json() { Set<City> citySet = new LinkedHashSet<City>(); citySet.add(new City(1,"廣州")); citySet.add(new City(2,"珠海")); JSONArray jSONArray = JSONArray.fromObject(citySet); String jsonJAVA = jSONArray.toString(); System.out.println(jsonJAVA); //[{"id":1,"name":"廣州"},{"id":2,"name":"珠海"}] } private static void javabeanlist2json() { List<City> cityList = new ArrayList<City>(); cityList.add(new City(1,"中山")); cityList.add(new City(2,"佛山")); Province province = new Province(1,"廣東",cityList); JSONArray jSONArray = JSONArray.fromObject(province); String jsonJAVA = jSONArray.toString(); System.out.println(jsonJAVA); /* [ { "id":1, "name":"廣東" "cityList":[{"id":1,"name":"中山"},{"id":2,"name":"佛山"}], } ] */ } private static void map2json() { List<City> cityList = new ArrayList<City>(); cityList.add(new City(1,"中山")); cityList.add(new City(2,"佛山")); Map<String,Object> map = new LinkedHashMap<String,Object>(); map.put("total",cityList.size());//表示集合的長度 map.put("rows",cityList);//rows表示集合 JSONArray jSONArray = JSONArray.fromObject(map); String jsonJAVA = jSONArray.toString(); System.out.println(jsonJAVA); //[{"total":2,"rows":[{"id":1,"name":"中山"},{"id":2,"name":"佛山"}]}] jsonJAVA = jsonJAVA.substring(1,jsonJAVA.length()-1); System.out.println(jsonJAVA); } }
把要解析成JSON 的javaBena對象、集合放進下面這段代碼便可!java
JSONArray jSONArray = JSONArray.fromObject(map);
不管放進去什麼,返回的都是數組json