Home >Java >javaTutorial >How to automatically add properties of JSONObject in Java?

How to automatically add properties of JSONObject in Java?

WBOY
WBOYforward
2023-08-19 14:41:04718browse

How to automatically add properties of JSONObject in Java?

A JSONObject is an unordered collection of name/value pairs and parses text from a string to generate something like Object that maps to . However, we can use the increment() method of the JSONObject class to automatically increment the properties of JSONObject. If there is no such attribute, create an attribute with the value 1. If such a property exists and it is an integer, long, double, or float, then it is incremented by one.

Syntax

public JSONObject increment(java.lang.String key) throws JSONException

Example

import org.json.JSONException;
import org.json.JSONObject;
public class IncrementJSONObjectTest {
   public static void main(String[] args) throws JSONException {
<strong>      </strong>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));
   }
}

Output

{
 "year": 2019,
 "age": 25
}
{
 "year": 2020,
 "age": 26
}
{
 "year": 2021,
 "age": 27
}
{
 "year": 2022,
 "age": 28
}

The above is the detailed content of How to automatically add properties of JSONObject in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete