Home > Java > javaTutorial > How to Extract \'id\' and \'loc\' Values from a Nested JSONArray in Java?

How to Extract \'id\' and \'loc\' Values from a Nested JSONArray in Java?

Mary-Kate Olsen
Release: 2024-11-27 05:13:11
Original
268 people have browsed it

How to Extract

Accessing "id" and "loc" Values from a Nested JSONArray in Java

When parsing JSON data in Java, it's common to encounter nested structures, such as JSONArrays within JSONObjects. Accessing specific values within these nested structures can be a bit tricky for beginners.

Problem:

Consider the following JSON data:

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

The goal is to iterate through the "record" JSONArray and access the "id" and "loc" values for each record.

Solution:

To access the members of an item in a JSONArray, you can use the getJSONObject(int) method. The following code demonstrates how to achieve this:

JSONObject req = new JSONObject(join(loadStrings(data.json),""));
JSONObject locs = req.getJSONObject("locations");
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");
    // ...
}
Copy after login

Within the for-loop:

  • recs.length() provides the number of elements in the "record" JSONArray.
  • recs.getJSONObject(i) returns a JSONObject representing the i-th record.
  • rec.getInt("id") retrieves the integer value of the "id" key.
  • rec.getString("loc") retrieves the string value of the "loc" key.

These retrieved values can then be used for further processing or operations.

The above is the detailed content of How to Extract \'id\' and \'loc\' Values from a Nested 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