String jsonStr = "{\"age\":26}"; JSONObject jsonObj = JSONObject.fromObject(jsonStr); int age = jsonObj.getInt("age"); System.out.println(age); // Output: 26
String jsonStr = "{\"employee\":{\"name\":\"John\", \"age\":35, \"salary\":5000}}"; JSONObject jsonObj = JSONObject.fromObject(jsonStr); JSONObject empObj = jsonObj.getJSONObject("employee"); int salary = empObj.getInt("salary"); System.out.println(salary); // Output: 5000In this example, we have a nested JSON object that represents an employee with name, age, and salary fields. We first parse the JSON string into a JSONObject using the fromObject() method. Then we retrieve the "employee" object using the getJSONObject() method and store it in the empObj variable. Finally, we use the getInt() method to retrieve the salary of the employee and store it in the salary variable. The package library used in these examples is net.sf.json.