Due
Today, look at the code found why people did not write the code to remove an element but there is no element of it?
Later found the code gets a substring removed an element in the front, the results of the parent nor the element of the string.
phenomenon
Original JSON string is like this: { "a": { "a1": "va1", "a2": "va2"}}
String jsonString = "{\"a\":{\"a1\":\"va1\",\"a2\":\"va2\"}}";
com.alibaba.fastjson.JSONObject json= com.alibaba.fastjson.JSONObject.parseObject(jsonString);
com.alibaba.fastjson.JSONObject aJson = json.getJSONObject("a");
aJson.remove("a1");
System.out.println(json.toJSONString());
Do you think the result of the output of the code above is what is it?
The net effect is: { "a": { " a2": "va2"}}
Explanation
fastjson in JSONObject using HashMap or json LinkedHashMap to save the key-value pairs, getObject (String key) is actually invoked map of get (String key) method, the returned object is a map of the reference object.
It means the following questions:
Map<String, List<String>> map = new HashMap<>();
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
map.put("aa", list);
List<String> aaList = map.get("aa");
aaList.remove(0);
List<String> aList = map.get("aa");
aList.forEach(System.out::println);
When the modified object acquired when, map objects will be changed, and therefore the fastjson JSONObject the substring modification causes a corresponding change in the parent sequence.