Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is the JSON code I’ve to access string values within a JSONArray:

{

  "locations": {

    "record": [

      {

        "id": 8817,

        "loc": "NEW YORK CITY"

      },

      {

        "id": 2873,

        "loc": "UNITED STATES"

      },

      {

        "id": 1501

        "loc": "NEW YORK STATE"

      }

    ]

  }

}

My code:

JSONObject req = new JSONObject(join(loadStrings(data.json),""));

JSONObject locs = req.getJSONObject("locations");

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

Here, I need to access the "record" JSONArray. Can anyone tell me how to do this?

1 Answer

0 votes
by (19.7k points)

You can use JSONArray.getJSONObject(int), and JSONArray.length() to create your for-loop like below: 

for (int i = 0; i < recs.length(); ++i) {

    JSONObject rec = recs.getJSONObject(i);

    int id = rec.getInt("id");

    String loc = rec.getString("loc");

    // ...

}

Interested in Java? Check out this Java Certification by Intellipaat.    

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...