起初:我知道,有很多這樣的問題,但答案沒有幫助。我是 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" 開頭的元素。現在我想訪問所有經緯度和名稱。有很多示例如何訪問元素,我知道但它們不起作用,例如這不起作用:
JSONObject jsonObj = new JSONObject(string);
jsonObj.getString("lat");
此外,我有數百個元素,我想訪問所有 lats、所有 lons 和所有名稱。我怎麼做?我看到的大多數示例都是針對簡單的 json 對象,還是我只是理解錯了?
您首先需要將“元素”屬性作為 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
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句