JSONObject là tập hợp không thứ tự các cặp name/value và parse text từ String tạo object dạng map. Tuy nhiên, chúng ta có thể tự động tăng thuộc tính của JSONObject dùng phương thức increment() của lớp JSONObject. Nếu chưa có property, tạo mới với giá trị 1. Nếu đã có và là Integer, Long, Double hoặc Float thì cộng 1.
Cú pháp
public JSONObject increment(java.lang.String key) throws JSONException
Ví dụ
import org.json.JSONException; import org.json.JSONObject; public class IncrementJSONObjectTest { public static void main(String[] args) throws JSONException { JSONObject jsonObj = new JSONObject(); jsonObj.put("year", 2019); jsonObj.put("age", 25); System.out.println(jsonObj.toString(3)); jsonObj.increment("year").increment("age"); System.out.println(jsonObj.toString(3)); jsonObj.increment("year").increment("age"); System.out.println(jsonObj.toString(3)); jsonObj.increment("year").increment("age"); System.out.println(jsonObj.toString(3)); } }
Kết quả
{ "year": 2019, "age": 25 } { "year": 2020, "age": 26 } { "year": 2021, "age": 27 } { "year": 2022, "age": 28 }