Reputation: 955
I have been dabbling with JSON and I see that in the documentation (JAVA), JSONObject's put() and accumulate() pretty much do the same thing?
What is that about?
Upvotes: 10
Views: 25617
Reputation: 955
I saw the Java Source Code for JSONObject and the difference between accumulate and put is that with accumulate(String key,Object Value), if there exists some value for "key" then the Object is checked for being an array, if it is an array then the "value" is added to the array else an array is created for this key.
In put, however, the key if it exists, it's value is replaced by the value - "value"
Here is the source of 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;
}
And here is the code for 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;
}
Upvotes: 28