Home > Java > javaTutorial > How to Access Members of a JSONArray in Java?

How to Access Members of a JSONArray in Java?

Linda Hamilton
Release: 2024-11-28 14:35:12
Original
269 people have browsed it

How to Access Members of a JSONArray in Java?

Accessing Members of Items in a JSONArray with Java

When working with JSON data, it's often necessary to access specific values within JSON arrays. A JSONArray represents a list of JSON objects in a JSON document. This article will guide you on how to access and retrieve string values from within a JSONArray using Java.

Consider the following sample JSON:

{
  "locations": {
    "record": [
      {
        "id": 8817,
        "loc": "NEW YORK CITY"
      },
      {
        "id": 2873,
        "loc": "UNITED STATES"
      },
      {
        "id": 1501
        "loc": "NEW YORK STATE"
      }
    ]
  }
}
Copy after login

Once you have access to the record JSONArray, you can use the following steps to retrieve the "id" and "loc" values for each record:

  1. Iterate through the JSONArray: Use the JSONArray.length() method to determine the number of records in the array and use a for loop to iterate through each record.
  2. Get the JSONObject for each record: For each record in the loop, use the JSONArray.getJSONObject(int) method to retrieve the corresponding JSONObject.
  3. Extract the values: Use the JSONObject methods to extract the specific values you need. For example, JSONObject.getInt("id") will give you the integer value for the "id" field, and JSONObject.getString("loc") will give you the string value for the "loc" field.

Here's a sample code that demonstrates accessing the "id" and "loc" values:

import org.json.JSONArray;
import org.json.JSONObject;

... // Load JSON data as before

JSONArray recs = locs.getJSONArray("record");

for (int i = 0; i < recs.length(); ++i) {
    JSONObject rec = recs.getJSONObject(i);
    int id = rec.getInt("id");
    String loc = rec.getString("loc");
    // Process id and loc as needed...
}
Copy after login

By following these steps, you can efficiently navigate and extract specific values from within a JSONArray, enabling you to consume and manipulate JSON data in your Java applications.

The above is the detailed content of How to Access Members of a JSONArray in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template