我需要将JSONObject转换为Map。
我注意到JSONObject有一个.toMap()方法..。
出于好奇,我注意到它有一个私人成员地图,它保存着JSONObject的地图.
但是当我查看toMap()方法时,我看到他们实际上创建了一个新的Map实例,并在整个JSONObject上迭代,而他们已经拥有一个私有成员了?
因此,在构建JSONObject时,他们已经完成了这项工作,但是当调用toMap()时,它们会再次这样做吗?
为什么toMap()实现不是简单的
new HashMap(this.map);来自JSONObject源代码:
/**
* The map where the JSONObject's properties are kept.
*/
private final Map<String, Object> map;私人成员几乎所有的获取方法都在质疑。
/**
* Put a key/value pair in the JSONObject. If the value is null, then the
* key will be removed from the JSONObject if it is present.
*
* @param key
* A key string.
* @param value
* An object which is the value. It should be of one of these
* types: Boolean, Double, Integer, JSONArray, JSONObject, Long,
* String, or the JSONObject.NULL object.
* @return this.
* @throws JSONException
* If the value is non-finite number or if the key is null.
*/
public JSONObject put(String key, Object value) throws JSONException {
if (key == null) {
throw new NullPointerException("Null key.");
}
if (value != null) {
testValidity(value);
this.map.put(key, value);
} else {
this.remove(key);
}
return this;
}在每个构造函数场景中调用put方法来填充私有映射成员。
/**
* Returns a java.util.Map containing all of the entries in this object.
* If an entry in the object is a JSONArray or JSONObject it will also
* be converted.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return a java.util.Map containing the entries of this object
*/
public Map<String, Object> toMap() {
Map<String, Object> results = new HashMap<String, Object>();
for (Entry<String, Object> entry : this.entrySet()) {
Object value;
if (entry.getValue() == null || NULL.equals(entry.getValue())) {
value = null;
} else if (entry.getValue() instanceof JSONObject) {
value = ((JSONObject) entry.getValue()).toMap();
} else if (entry.getValue() instanceof JSONArray) {
value = ((JSONArray) entry.getValue()).toList();
} else {
value = entry.getValue();
}
results.put(entry.getKey(), value);
}
return results;
}toMap创建了一个新的HashMap,而文学重复了构造过程
我觉得他们只是白白用了一个新的实例..。
我是不是遗漏了什么?
编辑:所以在阅读了注释之后,我可以接受新的实例,因为我们不希望更改引用。尽管如此,为什么实现不是一个简单的
return new HashMap(this.map);为什么要再次迭代JSONObject呢?
发布于 2019-06-18 16:05:42
为什么toMap()实现不是简单的 新HashMap(this.map);
因为这只是整个对象图的浅表副本,所以它只包含复制的“当前”级别。
如果仔细观察,您会发现toMap正在对每个子对象调用toMap,从而创建了深度复制。
https://stackoverflow.com/questions/56652746
复制相似问题