Java不像PHP解析和生產JSON老是一個比較痛苦的過程。可是使用JSONObject和JSONArray會讓整個過程相對舒服一些。html
須要依賴的包:commons-lang.jar commons-beanutils.jar commons-collections.jar commons-logging.jar ezmorph.jar json-lib-2.2.2-jdk15.jarjava
1. 建立一個JSONObject對象:web
package com.yunos.tv.video.resource.controller.web; 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", "ZHULI"); jsonObject.put("age", "30"); jsonObject.put("workIn", "ALI"); System.out.println("jsonObject1:" + jsonObject); //建立JsonObject第二種方法 HashMap<String, String> hashMap = new HashMap<String, String>(); hashMap.put("UserName", "ZHULI"); hashMap.put("age", "30"); hashMap.put("workIn", "ALI"); System.out.println("jsonObject2:" + JSONObject.fromObject(hashMap)); //建立一個JsonArray方法1 JSONArray jsonArray = new JSONArray(); jsonArray.add(0, "ZHULI"); jsonArray.add(1, "30"); jsonArray.add(2, "ALI"); System.out.println("jsonArray1:" + jsonArray); //建立JsonArray方法2 ArrayList<String> arrayList = new ArrayList<String>(); 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 = new JSONObject(); jsonObject2.put("UserName", "ZHULI"); jsonObject2.put("age", "30"); jsonObject2.put("workIn", "ALI"); jsonObject2.element("Array", arrayList); System.out.println("jsonObject2:" + jsonObject2); } }
結果:json
jsonObject1:{"UserName":"ZHULI","age":"30","workIn":"ALI"} jsonObject2:{"workIn":"ALI","age":"30","UserName":"ZHULI"} jsonArray1:["ZHULI","30","ALI"] jsonArray2:["ZHULI","30","ALI"] jsonArray FROM HASHMAP:[{"workIn":"ALI","age":"30","UserName":"ZHULI"}] jsonObject2:{"UserName":"ZHULI","age":"30","workIn":"ALI","Array":["ZHULI","30","ALI"]}
解析JSON字符串:數組
package com.yunos.tv.video.resource.controller.web; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class Test { public static void main(String[] args) { 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("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) + " "); } } } }
返回:ide
UserName:ZHULI Array:ZHULI Array:30 Array:ALI