學習筆記:建立JSONObject物件:
package ............
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", "張三");
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", ""
hashMap.put("age", "30");
hashMap.put("workIn", "ALI");
System.out.println("jsonObject2:" + JSONObject.fromObject(hashMap));
//建立一個JsonArray方法1
JSONArray jsonArray = new JSONArray();
jsonArray.add(0, ""張三");
jsonArray.add(1, "30");
jsonArray.add(2, "ALI");
System.out.println("jsonArray1:" + jsonArray);
//建立JsonArray方法2
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("張三");
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", "張三");
jsonObject2.put("age", "30");
jsonObject2.put("workIn", "ALI");
jsonObject2.element("Array", arrayList);
System.out.println("jsonObject2:" + jsonObject2);
}
}
結果:
jsonObject1:{"UserName":"張三","age":"30","workIn":"ALI"}
jsonObject2:{"workIn":"ALI","age":"30","UserName":"張三"}
jsonArray1:["張三","30","ALI"] jsonArray2:["張三","30","ALI"]
jsonArray FROM HASHMAP:[{"workIn":"ALI","age":"30","UserName":"張三"}]
jsonObject2:
{"UserName":"張三","age":"30","workIn":"ALI","Array":["張三","30","ALI"]}
解析JSON字元:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
String jsonString = "{\"UserName\":\"張三\",\"age\":\"30\",\"workIn\":\"ALI\",\"Array\":[\"張三\",\"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:張三
array:張三 array:30 array: ALI