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

How to automatically add properties of JSONObject in Java?

WBOY
Release: 2023-08-19 14:41:04
forward
717 people have browsed it

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
Copy after login

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));
   }
}
Copy after login

Output

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

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template