Home >Java >javaTutorial >How to Access and Extract Values from a Nested JSONArray in Java?

How to Access and Extract Values from a Nested JSONArray in Java?

DDD
DDDOriginal
2024-11-26 06:23:10291browse

How to Access and Extract Values from a Nested JSONArray in Java?

Accessing Member Values from a JSONArray in Java

Navigating through a JSONArray can be a challenge for those new to JSON parsing. Let's consider a scenario where you need to retrieve specific values from a nested JSON structure.

Suppose you have a JSON file with the following structure:

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

Using Java's JSON parsing capabilities, you can access the "record" JSONArray using the following code:

JSONObject req = new JSONObject(join(loadStrings(data.json),""));
JSONObject locs = req.getJSONObject("locations");
JSONArray recs = locs.getJSONArray("record");

To iterate through the "record" JSONArray and extract the "id" and "loc" values, you can employ the following loop:

for (int i = 0; i < recs.length(); ++i) {
    JSONObject rec = recs.getJSONObject(i);
    int id = rec.getInt("id");
    String loc = rec.getString("loc");
    // ...
}

Here's how each line of code contributes to the solution:

  • recs.length(): Obtains the length of the JSONArray, indicating the number of records it contains.
  • recs.getJSONObject(i): Retrieves the ith JSONObject within the JSONArray.
  • rec.getInt("id") and rec.getString("loc"): Extracts the "id" (an integer) and "loc" (a string) values from the JSONObject.
  • The ... represents the subsequent operations you can perform with the extracted values.

By combining these techniques, you'll be able to efficiently access and utilize the data within a JSONArray in your Java application.

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

Statement:
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