JSONObject obj = new JSONObject("{ \"name\":\"John\", \"age\":30 }"); String name = obj.optString("name", "Unknown"); System.out.println(name); // Output: "John"
JSONObject obj = new JSONObject("{ \"name\":\"John\", \"age\":30 }"); int age = obj.optInt("age", -1); System.out.println(age); // Output: 30In this example, the `optInt` method is used to retrieve the value of the "age" key from the JSON object. If the key is not found or the value is null, the default value of -1 is returned. The org.json package library is used in these examples.