The java org.json JSONArray getJSONObject method is a part of the org.json library package. This method is used to extract a specific JSONObject from an array.
Example 1:
Suppose we have a JSON array containing multiple user objects with their details like name, age, and email. We can use the getJSONObject method to extract the details of the user whose name matches a specified value.
JSONObject user = null; for (int i = 0; i < jsonArray.length(); i++) { if (jsonArray.getJSONObject(i).getString("name").equals("Sarah")) { user = jsonArray.getJSONObject(i); break; } }
System.out.println(user); // prints {"name":"Sarah","age":30,"email":"[email protected]"}
In the above example, we iterate over the array and check if the user's name is Sarah. If it matches, we extract the entire object and store it in a JSONObject variable.
Example 2:
Suppose we have a JSON array containing all the exam scores of a student. We want to extract the highest score.
int maxScore = Integer.MIN_VALUE; for (int i = 0; i < jsonArray.length(); i++) { JSONObject subjectScore = jsonArray.getJSONObject(i); int score = subjectScore.getInt("score"); if (score > maxScore) { maxScore = score; } }
System.out.println("Max score: " + maxScore); // prints Max score: 95
In the above example, we iterate over the array and extract the score from each object. We keep track of the highest score using a variable and update it whenever we encounter a higher score. Finally, we print the highest score.
The package library used in these examples is org.json.
Java JSONArray.getJSONObject - 30 examples found. These are the top rated real world Java examples of org.json.JSONArray.getJSONObject extracted from open source projects. You can rate examples to help us improve the quality of examples.