前面我们在使用Strus2的时候,Struts2自带了组件能够让JavaBean对象、集合转成是JSON,不用我们自己拼接…这是非常方便的。但是,我们不一定使用Struts2框架来做开发呀。因此,我们还得学习使用第三方库来将JavaBean对象、集合转成JSON
导入开发包- commons-io-2.0.1.jar
- commons-lang-2.5.jar
- commons-collections-3.1.jar
- commons-beanutils-1.7.0.jar
- ezmorph-1.0.3.jar
- json-lib-2.1-jdk15.jar
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对象、集合放进下面这段代码即可!
JSONArray jSONArray = JSONArray.fromObject(map);
无论放进去什么,返回的都是数组