1、JAR包簡介html
要使程序能夠運行必須引入JSON-lib包,JSON-lib包同時依賴於如下的JAR包:java
1.commons-lang.jarjson
2.commons-beanutils.jar數組
3.commons-collections.jarspa
4.commons-logging.jarcode
5.ezmorph.jarhtm
6.json-lib-2.2.2-jdk15.jar對象
2、JSONObject(json對象),JSONArray(json數組)的建立blog
import java.util.ArrayList; import java.util.HashMap; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class Test { public static void main(String[] args) { //JsonObject和JsonArray區別就是JsonObject是對象形式,JsonArray是數組形式 //建立JsonObject第一種方法 JSONObject jsonObject = new JSONObject(); jsonObject.put("UserName", "xxb"); jsonObject.put("age", "27"); System.out.println("jsonObject1:" + jsonObject); //建立JsonObject第二種方法 HashMap<String, String> hashMap = new HashMap<String, String>(); hashMap.put("UserName", "xxb"); hashMap.put("age", "27"); System.out.println("jsonObject2:" + JSONObject.fromObject(hashMap)); //建立一個JsonArray方法1 JSONArray jsonArray = new JSONArray(); jsonArray.add(0, "xxb"); jsonArray.add(1, "27"); System.out.println("jsonArray1:" + jsonArray); //建立JsonArray方法2 ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("xxb"); arrayList.add("27"); System.out.println("jsonArray2:" + JSONArray.fromObject(arrayList)); //若是JSONArray解析一個HashMap,則會將整個對象的放進一個數組的值中 System.out.println("jsonArray FROM HASHMAP:" + JSONArray.fromObject(hashMap)); //組裝一個複雜的JSONArray JSONObject jsonObject2 = new JSONObject(); jsonObject2.put("UserName", "xxb"); jsonObject2.put("age", "27"); jsonObject2.element("Array", arrayList); System.out.println("jsonObject2:" + jsonObject2); } }
結果:element
jsonObject1:{"UserName":"xxb","age":"27"}
jsonObject2:{"age":"27","UserName":"xxb"}
jsonArray1:["xxb","27"]
jsonArray2:["xxb","27"]
jsonArray FROM HASHMAP:[{"age":"27","UserName":"xxb"}]
jsonObject2:{"UserName":"ZHULI","age":"30","Array":["ZHULI","30","ALI"]}
2、解析JSON字符串
import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class Test { public static void main(String[] args) { String jsonString = "{\"UserName\":\"xxb\",\"age\":\"27\",\"Array\":[\"xxb\",\"27\"]}"; //將Json字符串轉爲java對象 JSONObject obj = JSONObject.fromObject(jsonString); //獲取Object中的UserName if (obj.has("UserName")) { System.out.println("UserName:" + obj.getString("UserName")); } //獲取ArrayObject if (obj.has("Array")) { JSONArray transitListArray = obj.getJSONArray("Array"); for (int i = 0; i < transitListArray.size(); i++) { System.out.print("Array:" + transitListArray.getString(i) + " "); } } } }
結果:
UserName:xxb
Array:xxb Array:27