What is the difference between accumulating and delivering a JSONObject?

I was doing JSON, and I see that in the (JAVA) documentation, JSONObject put () and accumulate () pretty much do the same thing?

What does it mean?

+6
source share
1 answer

I saw the Java source code for JSONObject, and the difference between accumulate and put is that with accumulation (String key, Object Value), if there is a specific value for the "key", then the object is checked for an array, if it is an array, then "value" is added to the array; otherwise, an array is created for this.

In the case, however, the key, if it exists, its value is replaced by the value - "value"

Here is the source of the accumulation of JSONObject (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; } 
+14
source

Source: https://habr.com/ru/post/983381/


All Articles