The java org.json package provides classes for handling JSON data in Java. The JSONObject class has a method called optLong, which is used to retrieve a Long value from the JSONObject if it exists, or returns a default value if it does not exist.
Here are some examples for using the optLong method:
Example 1: JSONObject obj = new JSONObject("{\"id\": 1234, \"name\": \"John Doe\"}"); Long id = obj.optLong("id", -1); // returns 1234 Long age = obj.optLong("age", -1); // returns -1
In this example, we create a JSONObject with an "id" field and a "name" field. We then use the optLong method to retrieve the value of the "id" field and assign it to the variable "id". We also try to retrieve the value of the "age" field, which does not exist in the JSONObject, so the method returns the default value of -1.
Example 2: JSONObject obj = new JSONObject(); obj.put("price", "9.99"); Long price = obj.optLong("price", 0); // returns 0
In this example, we create an empty JSONObject and add a "price" field with a String value "9.99". We then use the optLong method to retrieve the value of the "price" field, which is a String, so the method returns the default value of 0.
Package library: The org.json package is part of the Java Development Kit (JDK) and does not require any additional library.
Java JSONObject.optLong - 30 examples found. These are the top rated real world Java examples of org.json.JSONObject.optLong extracted from open source projects. You can rate examples to help us improve the quality of examples.