A JSONObject เป็นคอลเลกชันที่ไม่เรียงลำดับของ ชื่อ/ค่า จับคู่และแยกข้อความจากสตริงเพื่อสร้าง แผนที่ -เหมือนวัตถุ อย่างไรก็ตาม เราสามารถเพิ่มอัตโนมัติ คุณสมบัติของ JSONObject โดยใช้ increment() เมธอดของคลาส JSONObject หากไม่มีคุณสมบัติดังกล่าว ให้สร้างด้วยค่า 1 . หากมีคุณสมบัติดังกล่าว และหากเป็นจำนวนเต็ม ลอง สองเท่า หรือลอย ให้เพิ่มคุณสมบัติดังกล่าวเข้าไป
ไวยากรณ์
public JSONObject increment(java.lang.String key) throws JSONException
ตัวอย่าง
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));
}
} ผลลัพธ์
{
"year": 2019,
"age": 25
}
{
"year": 2020,
"age": 26
}
{
"year": 2021,
"age": 27
}
{
"year": 2022,
"age": 28
}