2015-03-05 14 views

Trả lời

14

Tôi thấy mã nguồn Java cho JSONObject và sự khác biệt giữa tích lũy và đặt là tích lũy (String key, Object Value), nếu tồn tại một số giá trị cho "key" thì Object được kiểm tra là một mảng, nếu nó là một mảng thì giá trị "" được thêm vào mảng khác, một mảng được tạo cho khóa này.

Trong đặt, tuy nhiên, chìa khóa nếu nó tồn tại, giá trị của nó được thay thế bằng giá trị - "giá trị"

Đây là nguồn gốc của JSONObject tích lũy (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; 
} 

Và đây là mã cho JSONObject đặt (Chuỗi khóa, Giá trị đối tượng)

/** 
* 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; 
} 
+0

Vì vậy, nếu tôi cần phải tạo một đối tượng đơn giản-level-json, đó là tốt hơn về hiệu suất, tích lũy hoặc đặt? –

+0

@HamzehSoboh Tôi nghĩ rằng việc đặt sẽ tốt hơn, nhưng trừ khi đối tượng của bạn là rất lớn, tôi không nghĩ sẽ có sự khác biệt lớn về hiệu suất. –

+0

Câu trả lời hay. Cảm ơn! –

Các vấn đề liên quan