Java不像PHP解析和生產JSON總是一個比較痛苦的過程。但是使用JSONObject和JSONArray會讓整個過程相對舒服一些。
需要依賴的包:commons-lang.jar commons-beanutils.jar commons-collections.jar commons-logging.jar ezmorph.jar json-lib-2.2.2-jdk15.jar
1. 建立一個JSONObject物件:
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);
}
}
結果:
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) + " ");
}
}
}
}
返回:
UserName:ZHULI
Array:ZHULI Array:30 Array:ALI