Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีเพิ่มค่าคุณสมบัติ JSONObject แบบอัตโนมัติใน Java

JSONObject เป็นคอลเลกชันแบบไม่มีลำดับของคู่ ชื่อ/ค่า และแปลงข้อความจาก String เพื่อสร้างอ็อบเจกต์แบบ map แต่เราสามารถ เพิ่มค่าอัตโนมัติ (auto-increment) คุณสมบัติของ JSONObject ได้โดยใช้เมธอด increment() ของคลาส JSONObject หากไม่มีคุณสมบัตินั้น จะสร้างใหม่ด้วยค่า 1 หากมีอยู่แล้วและเป็น Integer, Long, Double หรือ Float จะบวก 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
}