加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

JSONObject accumulate和put之间有什么区别?

发布时间:2020-12-16 19:52:57 所属栏目:百科 来源:网络整理
导读:我一直在使用 JSON,我在文档(JAVA)中看到,JSONObject的put()和accumulate()几乎做同样的事情? 那是什么? 我看到了JSONObject的Java源代码,accumulate和put之间的区别在于使用accumulate(String key,Object Value),如果存在“key”的某个值,则检查Object是
我一直在使用 JSON,我在文档(JAVA)中看到,JSONObject的put()和accumulate()几乎做同样的事情?

那是什么?

我看到了JSONObject的Java源代码,accumulate和put之间的区别在于使用accumulate(String key,Object Value),如果存在“key”的某个值,则检查Object是否为数组,如果是然后将“value”添加到数组中,否则将为此键创建一个数组.

然而,在put中,如果密钥存在,它的值将被值替换 – “value”

这是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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读