- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to auto-increment the property of a JSONObject in Java?
A JSONObject is an unordered collection of name/value pairs and parses text from a String to produce a map-like object. However, we can auto-increment the property of a JSONObject using the increment() method of JSONObject class. If there is no such property, create one with a value of 1. If there is such a property and if it is an Integer, Long, Double or Float then add one to it.
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 { 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 }
Advertisements
To Continue Learning Please Login
Login with Google