需要依赖的jar包: commons-lang.jar commons-beanutils.jar commons-collections.jar commons-logging.jar ezmorph.jar json-lib-2.2.2-jdk15.jar
首先简单地看一下JSONObject,JSONArray对象的创建以及Json字符串的解析:
packagecom.peter.jsonobj.test;
importjava.util.ArrayList;
importjava.util.HashMap;
importnet.sf.json.JSONArray;
importnet.sf.json.JSONObject;
publicclassTest2 {
publicstaticvoidmain(String[] args) {
//JsonObject和JsonArray区别就是JsonObject是对象形式,JsonArray是数组形式
//创建JsonObject第一种方法
JSONObject jsonObject = newJSONObject();
jsonObject.put("UserName","ZHULI");
jsonObject.put("age","30");
jsonObject.put("workIn","ALI");
System.out.println("jsonObject1:"+ jsonObject);
//创建JsonObject第二种方法
HashMap hashMap = newHashMap();
hashMap.put("UserName","ZHULI");
hashMap.put("age","30");
hashMap.put("workIn","ALI");
System.out.println("jsonObject2:"+ JSONObject.fromObject(hashMap));
//创建一个JsonArray方法1
JSONArray jsonArray = newJSONArray();
jsonArray.add(0,"ZHULI");
jsonArray.add(1,"30");
jsonArray.add(2,"ALI");
System.out.println("jsonArray1:"+ jsonArray);
//创建JsonArray方法2
ArrayList arrayList = newArrayList();
arrayList.add("ZHULI");
arrayList.add("30");
arrayList.add("ALI");
System.out.println("jsonArray2:"+ JSONArray.fromObject(arrayList));
//如果JSONArray解析一个HashMap,则会将整个对象的放进一个数组的值中
System.out.println("jsonArray FROM HASHMAP:"+ JSONArray.fromObject(hashMap));
//组装一个复杂的JSONArray
JSONObject jsonObject2 = newJSONObject();
jsonObject2.put("UserName","ZHULI");
jsonObject2.put("age","30");
jsonObject2.put("workIn","ALI");
jsonObject2.element("Array", arrayList);
System.out.println("jsonObject2:"+ jsonObject2);
//解析JSON字符串:
String jsonString = "{\"UserName\":\"ZHULI\",\"age\":\"30\",\"workIn\":\"ALI\",\"Array\":[\"ZHULI\",\"30\",\"ALI\"]}";
//将Json字符串转为java对象
JSONObject obj = JSONObject.fromObject(jsonString);
//获取Object中的UserName
if(obj.has("UserName")) {
System.out.println("UserName:"+ obj.getString(