Skip to content
Advertisement

How to access repeated elements in JSON object java?

At first: I know, there are many questions like this one, but all the answers don’t help. I am new to JSON and appreciate every answer.

I have a JSON object like this:

{
  "version": 0.6,
  "generator": "Overpass API 0.7.57 93a4d346",
  "osm3s": {
    "timestamp_osm_base": "2021-10-26T12:48:42Z",
    "copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
  },
  "elements": [
    {
      "type": "node",
      "id": 58489979,
      "lat": 52.5098189,
      "lon": 13.4073729,
      "tags": {
        "addr:city": "Berlin",
        "addr:country": "DE",
        "addr:housenumber": "83",
        "addr:postcode": "10179",
        "addr:street": "Alte Jakobstraße",
        "addr:suburb": "Mitte",
        "brand": "Netto Marken-Discount",
        "brand:wikidata": "Q879858",
        "brand:wikipedia": "de:Netto Marken-Discount",
        "name": "Netto Marken-Discount",
        "shop": "supermarket",
        "website": "http://netto-online.de/",
        "wheelchair": "no"
      }
    },
    {
      "type": "node",
      "id": 269479009,
      "lat": 52.5136840,
      "lon": 13.4060088,
      "tags": {
        "addr:city": "Berlin",
        "addr:country": "DE",
        "addr:housenumber": "12",
        "addr:postcode": "10179",
        "addr:street": "Fischerinsel",
        "addr:suburb": "Mitte",
        "contact:website": "http://www.edeka.de",
        "name": "Edeka Ungefroren",
        "opening_hours": "Mo-Sa 07:00-21:00",
        "shop": "supermarket",
        "toilets:wheelchair": "yes",
        "wheelchair": "yes"
      }
    }, ...
  ]
}

The JSON object can have hundreds of these elements which begin with "type" : "node". Now I want to access all lat, lon and names. There are many examples show how to access the elements, I know but they don’t work, for example, this doesn’t work:

JSONObject jsonObj = new JSONObject(string);
jsonObj.getString("lat");

Furthermore, I have hundreds of the elements and I want to access all lats, all lons, and all names. How do I do that? Most of the examples I saw, are for simple JSON objects or did I just understand them wrong?

Advertisement

Answer

You need first to get the “elements” property as a JSONArray. Then you can retrieve the JSONObject holding lat as follow:

JSONObject jsonObj = new JSONObject(string);
JSONArray resultArray = jsonObj.getJSONArray("elements");
for (int i = 0; i < resultArray.length(); i++) {
    JSONObject item = resultArray.getJSONObject(i);
     
    // Now you can retrieve the lat
    double lat = item.getDouble("lat");  // Not getString("lat") because lat is a number, not a string
    ...
}
Advertisement