一.JSONObject类
public class JSONObject extends
JSON implements Map<String, Object>,Cloneable,Serializable,InvocationHandler{}
JSONObject是通过继承Map<String,Object>实现的
public static final long serialVersionUID =1L;
public static final int DEFAULT_INITIAL_CAPACITY=16;
private final Map<String, Object> map;
public JSONObject(){
this(DEFAULT_INITIAL_CAPACITY,false);
}
public JSONObject(Map<String, Object> map) {
this.map=map;
}
看个具体的列子:
/**
* 将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中的方法。
具体的列子:
/**
* 将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}]
二.JSONArray类
public class JSONArray
extends JSON implements List<Object>, Cloneable, RandomAccess, Serializable
JSONArray是通过继承List对象实现的
构造方法:
public JSONArray()
public JSONArray(List<Object> list)
public JSONArray(int initialCapacity)
下面看个示例:
public class Test {
public static void main(String[] args) {
List<String> contentList = new ArrayList<>();
contentList.add("[\"HDC-51\"]");
contentList.add("[\"HDC-51\", \"HDC-55\"]");
contentList.add("[\"HDC-50\", \"HDC-55\", \"HDC-55-2\"]");
contentList.add("[\"HDC-51\", \"HDC-55\", \"HDC-55-2\",\"HDC-21N\"]");
System.out.println(contentList);
String macType ="HDC-50";
for (String content : contentList) {
try {
JSONArray contentArray = JSONArray.parseArray(content);
//System.out.println("contentArray前 : " + contentArray);
if (!contentArray.contains(macType)) {
contentArray.add(macType);
}
System.out.println("contentArray后 : " + contentArray);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
运行结果如下:
今天就先说到这里,后续还会继续探索源码的。