先展示测试运行代码(部分)
import com.alibaba.fastjson2.JSONObject;
System.out.println("=====");
JSONObject jsonObject = new JSONObject();
System.out.println(jsonObject);
System.out.println(jsonObject.isEmpty());
System.out.println(jsonObject.size());
System.out.println("=====");
jsonObject.put("data",new JSONObject().put("value1",1));
System.out.println(jsonObject);
System.out.println(jsonObject.isEmpty());
System.out.println(jsonObject.size());
for (String key : jsonObject.keySet()) {
Object value = jsonObject.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
System.out.println("=====");
JSONObject data =new JSONObject();
jsonObject.put("data",data.put("value2",2));
System.out.println(jsonObject);
System.out.println(jsonObject.isEmpty());
System.out.println(jsonObject.size());
for (String key : jsonObject.keySet()) {
Object value = jsonObject.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
JSONObject dataJson1 = jsonObject.getJSONObject("data");
System.out.println(dataJson1);
System.out.println("=====");
data.put("value3",3);
jsonObject.put("data",data);
System.out.println(jsonObject);
System.out.println(jsonObject.isEmpty());
System.out.println(jsonObject.size());
for (String key : jsonObject.keySet()) {
Object value = jsonObject.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
JSONObject dataJson2 = jsonObject.getJSONObject("data");
for (String key : dataJson2.keySet()) {
Object value = dataJson2.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
运行结果
=====
{}
true
0
=====
{}
false
1
Key: data, Value: null
=====
{}
false
1
Key: data, Value: null
null
=====
{"data":{"value2":2,"value3":3}}
false
1
Key: data, Value: {"value2":2,"value3":3}
Key: value2, Value: 2
Key: value3, Value: 3
我的疑问
为什么value1没有成功添加?
为什么value2先出现和value1相同的情况,显示没有成功添加,但在value3成功添加后又出现了?
如果出现添加value1和value2的类似错误,如何判断JSONObject为null或者没有键值对?