【问题标题】:How to access repeated elements in JSON object java?如何访问 JSON 对象 java 中的重复元素?
【发布时间】:2021-10-26 14:13:17
【问题描述】:

起初:我知道,有很多类似的问题,但所有的答案都无济于事。我是 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 对象,还是我理解错了?

【问题讨论】:

    标签: java json object repeat


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢。这正是我所需要的
    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 2013-01-02
    • 1970-01-01
    • 2019-09-30
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多