fastjson之JSONObject、JSONArray


JSONObject,JSONArray是JSON的兩個子類。

 

首先我們來看JSONObject源碼:

會發現JSONObject是繼承Map<String, Object>,並且都是使用的Map中的方法。可以說JSONObject相當於Map<String, Object>

看個具體的列子:

  /**
     * 將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"));
    }

運行結果:

{"key1":"value1","key2":"value2","key3":"value3"}
value2

 

看JSONArray的源碼:

會發現JSONArray是繼承List<Object>,並且都是使用的List中的方法。可以說JSONArray相當於List<Object>

具體的列子:

  /**
     * 將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);
    }

運行結果:

["home",60,true,{"id":1,"message":"Hello World","sendTime":1525237337937}]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM