若是要將數組、對象、Map、List轉換成JSON數據,那咱們須要一些jar包:html
json-lib-2.4-jdk15.jarjava
ezmorph-1.0.6.jarjson
commons-logging.jar數組
commons-lang.jareclipse
commons-collections.jar工具
commons-beanutils.jarspa
百度經驗:jingyan.baidu.com htm
WIN7對象
eclipseip
百度經驗:jingyan.baidu.com
1
將數組轉換爲JSON:
String[] arr = {"asd","dfgd","asd","234"};
JSONArray jsonarray = JSONArray.fromObject(arr);
System.out.println(jsonarray);
2
對象轉換成JSON:
UserInfo user = new UserInfo(1001,"張三");
JSONArray jsonArray = JSONArray.fromObject(user);
System.out.println( jsonArray );
3
把Map轉換成json, 要使用jsonObject對象:
Map<String, Object> map = new HashMap<String, Object>();
map.put("userId", 1001);
map.put("userName", "張三");
map.put("userSex", "男");
JSONObject jsonObject = JSONObject.fromObject(map);
System.out.println(jsonObject);
4
把List轉換成JSON數據:
List<UserInfo> list = new ArrayList<UserInfo>();
UserInfo user = new UserInfo(1001, "張三");
list.add(user);
list.add(user);
list.add(user);
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray);