JSONObject的數據用{}來表示,如:json
{ "id" : "123", "courseID" : "huangt-test", "title" : "提交做業"}
JSONArray是由JSONObject構成的數組,用[{},{}]來表示,如:數組
[{"id" : "123", "courseID" : "huangt-test", "title" : "提交做業"}, {"beginTime" : 1398873600000 "endTime"}] ;
接下來看一下具體的例子:this
package jsontest; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JSONObjectSample { // 建立JSONObject對象 private static JSONObject createJSONObject() { JSONObject jsonObject = new JSONObject(); jsonObject.put("username", "huangwuyi"); jsonObject.put("sex", "男"); jsonObject.put("QQ", "413425430"); jsonObject.put("Min.score", new Integer(99)); jsonObject.put("nickname", "夢中心境"); return jsonObject; } public static void main(String[] args) { JSONObject jsonObject = JSONObjectSample.createJSONObject(); // jsonObject:{"username":"huangwuyi","sex":"男","QQ":"413425430","Min.score":99,"nickname":"夢中心境"} System.out.println("jsonObject:" + jsonObject); boolean isArray = jsonObject.isArray(); //false boolean isEmpty = jsonObject.isEmpty(); //false boolean isNullObject = jsonObject.isNullObject(); //false // 添加屬性 jsonObject.element("address", "福建省廈門市"); // 返回一個JSONArray對象 JSONArray jsonArray = new JSONArray(); jsonArray.add(0, "this is a jsonArray value"); jsonArray.add(1, "another jsonArray value"); jsonObject.element("jsonArray", jsonArray); //獲取追加的名爲"jsonArray"的一個jsonArray JSONArray array = jsonObject.getJSONArray("jsonArray"); //{"username":"huangwuyi","sex":"男","QQ":"413425430","Min.score":99,"nickname":"夢中心境","address":"福建省廈門市","jsonArray":["this is a jsonArray value","another jsonArray value"]} System.out.println(jsonObject); // 根據key返回一個字符串 String username = jsonObject.getString("username"); // 把字符轉換爲 JSONObject String temp = jsonObject.toString(); JSONObject object = JSONObject.fromObject(temp); } }
注意一下JSONObject的put()和element()方法的區別:
public Object put (Object key, Object value):
將value映射到key下。若是此JSONObject對象以前存在一個value在這個key下,當前的value會替換掉以前的value
public JSONObject element (String key, Object value):
將鍵/值對放到這個JSONObject對象裏面。若是當前value爲空(null),那麼若是這個key存在的話,這個key就會移除掉。spa