如何自动增量 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