如何自動增量 Java 中 JSONObject 的屬性?
一個JSONObject是一個無序的名稱/值對集合,它將文字從 String 解析為生成map型物件。但是,我們可以使用 JSONObject 類中的increment()方法來自動增加 JSONObject 的屬性。如果沒有此類屬性,建立一個值為1的屬性。如果存在此類屬性,並且它是一個 Integer、Long、Double 或 Float,則向其中新增一個。
語法
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
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP