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.
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 { <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)); } }
{ "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!