gpt4 book ai didi

java - JSONObject.toMap() 实现

转载 作者:行者123 更新时间:2023-12-02 04:18:02 26 4
gpt4 key购买 nike

我需要将 JSONObject 转换为 Map。

我注意到 JSONObject 有一个 .toMap() 方法...

出于好奇,我深入研究了对象本身,我注意到它有一个私有(private)成员映射,其中包含 JSONObject 的映射...

但是当我查看 toMap() 方法时,我发现他们实际上创建了一个新的 Map 实例并迭代整个 JSONObject,而他们已经有了一个私有(private)成员?

所以他们在构造 JSONObject 时已经完成了工作,但是当调用 toMap() 时他们又做了一次?

为什么 toMap() 的实现并不简单

new HashMap(this.map);

来自 JSONObject 源代码:

 /**
* The map where the JSONObject's properties are kept.
*/
private final Map<String, Object> map;

私有(private)成员几乎每个get方法都在质疑

/**
* 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 方法来填充私有(private)映射成员

 /**
* 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?

最佳答案

Why toMap() implementation isnt simply

new HashMap(this.map);

因为这只是整个对象图的浅拷贝,因此它只包含复制的“当前”级别。

如果仔细观察,您会发现 toMap 正在对每个子对象调用 toMap,从而创建深层复制。

关于java - JSONObject.toMap() 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56652746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com