Home >Java >javaTutorial >How to Access String Values (e.g., \'loc\') from a JSONArray in Java?
Accessing String Values within a JSONArray in Java
When dealing with JSON data in Java, accessing string values within a JSONArray can be tricky for beginners. Let's delve into a solution to this common problem.
You have constructed your JSONObjects and retrieved the "record" JSONArray. To access the "id" and "loc" values within this JSONArray, you can utilize two methods:
JSONArray.getJSONObject(int) method: This method returns a specific JSONObject within the JSONArray at the specified index.
JSONArray.length() method: This method returns the number of elements in the JSONArray.
With these methods in mind, you can create a for-loop to iterate through the "record" JSONArray and retrieve the desired values:
for (int i = 0; i < recs.length(); ++i) { JSONObject rec = recs.getJSONObject(i); int id = rec.getInt("id"); String loc = rec.getString("loc"); // ... }
In this loop, the i variable represents the index of the current JSONObject within the JSONArray. The getJSONObject(i) method extracts the JSONObject at index i. You can then use the getInt("id") and getString("loc") methods to retrieve the values of the "id" and "loc" fields within that JSONObject.
The above is the detailed content of How to Access String Values (e.g., \'loc\') from a JSONArray in Java?. For more information, please follow other related articles on the PHP Chinese website!