Home > Java > javaTutorial > How Do I Access and Process JSON Array Objects in Java?

How Do I Access and Process JSON Array Objects in Java?

Patricia Arquette
Release: 2024-12-03 05:55:15
Original
641 people have browsed it

How Do I Access and Process JSON Array Objects in Java?

Accessing JSON Array Objects in Java

Accessing string values within a JSONArray in Java requires understanding how to navigate the JSON structure and retrieve the desired data.

Given a JSON object like the one provided:

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

To access the "id" and "loc" values in a for loop, use the following code:

JSONArray recs = req.getJSONObject("locations").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 the data as needed)
}
Copy after login

This code iterates through the records array, accessing each record as a JSON object. It then retrieves the "id" value as an integer using getInt("id") and the "loc" value as a string using getString("loc"). The processed data can then be used in subsequent operations.

The above is the detailed content of How Do I Access and Process JSON Array Objects 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