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}]
fastjson之JSONObject、JSONArray
原文地址:https://www.cnblogs.com/xuwenjin/p/8979706.html