JSONObject的accumulate和put方法有什么区别?

10

我一直在涉猎JSON,发现在文档中(JAVA),JSONObject的put()和accumulate()几乎是相同的操作?

这是怎么回事?


你使用的是哪个库? - Bastian Voigt
安卓一代,有什么区别吗? - Chintan Shah
1个回答

27

我看到了 JSONObject 的 Java 源代码,accumulate 和 put 的区别在于:使用 accumulate(String key,Object Value) 方法时,如果存在 "key" 的某个值,则会检查该对象是否为数组,如果是,则将 "value" 添加到该数组中,否则将为此键创建一个数组。

但是,在使用 put 方法时,如果存在该键,则其值将被替换为指定的值。

下面是 JSONObject accumulate(String key, Object Value) 的源代码:

/**
 * Appends {@code value} to the array already mapped to {@code name}. If
 * this object has no mapping for {@code name}, this inserts a new mapping.
 * If the mapping exists but its value is not an array, the existing
 * and new values are inserted in order into a new array which is itself
 * mapped to {@code name}. In aggregate, this allows values to be added to a
 * mapping one at a time.
 *
 * <p> Note that {@code append(String, Object)} provides better semantics.
 * In particular, the mapping for {@code name} will <b>always</b> be a
 * {@link JSONArray}. Using {@code accumulate} will result in either a
 * {@link JSONArray} or a mapping whose type is the type of {@code value}
 * depending on the number of calls to it.
 *
 * @param value a {@link JSONObject}, {@link JSONArray}, String, Boolean,
 *     Integer, Long, Double, {@link #NULL} or null. May not be {@link
 *     Double#isNaN() NaNs} or {@link Double#isInfinite() infinities}.
 */

  public JSONObject accumulate(String name, Object value) throws JSONException {
    Object current = nameValuePairs.get(checkName(name));
    if (current == null) {
        return put(name, value);
    }

    if (current instanceof JSONArray) {
        JSONArray array = (JSONArray) current;
        array.checkedPut(value);
    } else {
        JSONArray array = new JSONArray();
        array.checkedPut(current);
        array.checkedPut(value);
        nameValuePairs.put(name, array);
    }
    return this;
}

这里是JSONObject put (String key, Object value)的代码

 /**
 * Maps {@code name} to {@code value}, clobbering any existing name/value
 * mapping with the same name.
 *
 * @return this object.
 */
public JSONObject put(String name, boolean value) throws JSONException {
    nameValuePairs.put(checkName(name), value);
    return this;
}

那么,如果我需要创建一个简单的 - 一级 - JSON 对象,从性能角度来看,累加还是放置更好? - Hamzeh Soboh
1
@HamzehSoboh 我认为使用put会更好,但除非你的对象非常大,否则我不认为性能差异会很大。 - Chintan Shah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接