JSONObject,JSONArray是JSON的兩個子類。json
首先咱們來看JSONObject源碼:spa
會發現JSONObject是繼承Map<String, Object>,而且都是使用的Map中的方法。能夠說JSONObject至關於Map<String, Object>code
看個具體的列子:對象
/** * 將Map轉成JSONObject,而後添加元素,輸出 */ @Test public void testJsonObject() { Map<String, Object> testMap = new HashMap<>(); testMap.put("key1", "value1"); testMap.put("key2", "value2"); JSONObject jsonObj = new JSONObject(testMap); jsonObj.put("key3", "value3"); System.out.println(jsonObj); System.out.println(jsonObj.get("key2")); }
運行結果:blog
{"key1":"value1","key2":"value2","key3":"value3"} value2
看JSONArray的源碼:繼承
會發現JSONArray是繼承List<Object>,而且都是使用的List中的方法。能夠說JSONArray至關於List<Object>get
具體的列子:源碼
/** * 將List對象轉成JSONArray,而後輸出 */ @Test public void testJsonArray() { List<Object> list = new ArrayList<>(); list.add("home"); list.add(60); list.add(true); list.add(new XwjUser(1, "Hello World", new Date())); JSONArray jsonArr = JSONArray.parseArray(JSON.toJSONString(list)); System.out.println(jsonArr); }
運行結果:class
["home",60,true,{"id":1,"message":"Hello World","sendTime":1525237337937}]