如何在 Java 中自动增加 JSONObject 的属性?
javajsonobject oriented programmingprogramming更新于 2025/7/17 8:44:17
JSONObject 是无序的 名称/值 对集合,它解析字符串中的文本以生成 map 类对象。但是,我们可以使用 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
}
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

