如何访问 JSON 对象 java 中的重复元素?

How to access repeated elements in JSON object java?

起初:我知道,有很多这样的问题,但所有的答案都无济于事。我是 JSON 的新手,非常感谢您的回答。

我有一个这样的 JSON 对象:

{
  "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"
      }
    }, ...
  ]
}

JSON 对象可以有数百个以 "type" : "node" 开头的元素。现在我想访问所有 latlonnames。有很多例子展示了如何访问元素,我知道,但是 它们不起作用,例如,这个不起作用:

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

此外,我有数百个元素,我想访问所有 lats、所有 lons 和所有 names。我怎么做?我看到的大多数示例都是针对简单的 JSON 对象,还是我理解错了?

您首先需要获取“元素”属性 作为 JSONArray。然后您可以检索持有 lat 的 JSONObject,如下所示:

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
    ...
}