Home > Java > javaTutorial > How to Access String Values (e.g., \'loc\') from a JSONArray in Java?

How to Access String Values (e.g., \'loc\') from a JSONArray in Java?

DDD
Release: 2024-12-08 11:07:10
Original
549 people have browsed it

How to Access String Values (e.g.,

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");
    // ...
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template