import org.json.JSONObject; JSONObject student = new JSONObject("{ \"name\": \"John\", \"age\": 20 }"); int age = student.optInt("age", 0); // returns 20
import org.json.JSONObject; JSONObject library = new JSONObject("{ \"books\": [{ \"id\": 1, \"pages\": 100 }, { \"id\": 2, \"pages\": 200 }] }"); int pages = library.getJSONObject("books").getJSONObject("2").optInt("pages", 0); // returns 200In this example, we first get the "books" array from the JSON object, and then we get the second book object using its index (which is 1 because JSON arrays are zero-indexed). Finally, we retrieve the "pages" field as an integer using the optInt() method. The above code examples belong to the org.json package library in Java.