作者:18382457909@163.com | 来源:互联网 | 2023-10-11 10:38
JSONObject,JSONArray是JSON的两个子类。
首先我们来看JSONObject源码:
会发现JSONObject是继承Map,并且都是使用的Map中的方法。可以说JSONObject相当于Map
看个具体的列子:
/**
* 将Map转成JSONObject,然后添加元素,输出
*/
@Test
public void testJsonObject() {
Map 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,并且都是使用的List中的方法。可以说JSONArray相当于List
具体的列子:
/**
* 将List对象转成JSONArray,然后输出
*/
@Test
public void testJsonArray() {
List 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