我正在尝试从下面的JSON中检索“Maxspeed”字符串。 它遍历数组,但是当它到达“tag”对象并尝试检索“maxspeed”值时,它返回一个异常(下面)。
有谁知道为什么会这样? 任何帮助将不胜感激。
感谢。
例外:
org.json.JSONException: No value for maxspeed
爪哇:
JSONObject parentObject = new JSONObject(result);
JSONArray speedJSON = parentObject.getJSONArray("elements");
for (int i = 0; i < speedJSON.length(); i++) {
JSONObject element = (JSONObject) speedJSON.get(i);
if (!element.isNull("tags")) {
//JSONObject tags = (JSONObject) speedJSON.getJSONObject(i).get("tags");
String maxspeed = element.getString("maxspeed");
txtSpeed.setText(maxspeed+" here");
} else {
//Your error handling here...
}
}
//txtSpeed.setText(""+);
this.progressDialog.dismiss();
JSON:
{
"version": 0.6,
"generator": "Overpass API",
"osm3s": {
"timestamp_osm_base": "2015-03-16T20:10:02Z",
"copyright": "The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."
},
"elements": [
{
"type": "node",
"id": 768053039,
"lat": 54.9526671,
"lon": -7.7273348
},
{
"type": "node",
"id": 768053040,
"lat": 54.9498094,
"lon": -7.7176056
},
{
"type": "node",
"id": 768053041,
"lat": 54.9497066,
"lon": -7.7173174
},
{
"type": "node",
"id": 768053043,
"lat": 54.9495658,
"lon": -7.7170937
},
{
"type": "node",
"id": 768053044,
"lat": 54.9495035,
"lon": -7.7169816
},
{
"type": "node",
"id": 791492493,
"lat": 54.9494183,
"lon": -7.7168205
},
{
"type": "node",
"id": 795319854,
"lat": 54.9510427,
"lon": -7.7218262
},
{
"type": "node",
"id": 795320324,
"lat": 54.9509153,
"lon": -7.7213706
},
{
"type": "node",
"id": 1922546572,
"lat": 54.9502165,
"lon": -7.7190169
},
{
"type": "node",
"id": 1922546679,
"lat": 54.9504739,
"lon": -7.7199078
},
{
"type": "node",
"id": 1922546692,
"lat": 54.9500860,
"lon": -7.7185174
},
{
"type": "node",
"id": 1922602861,
"lat": 54.9517250,
"lon": -7.7241644
},
{
"type": "node",
"id": 1922622063,
"lat": 54.9514357,
"lon": -7.7231690
},
{
"type": "node",
"id": 2673934802,
"lat": 54.9498543,
"lon": -7.7177617
},
{
"type": "way",
"id": 64273241,
"nodes": [
768053039,
1922602861,
1922622063,
795319854,
795320324
],
"tags": {
"highway": "secondary",
"maxspeed": "60",
"name": "Port Road",
"oneway": "no",
"ref": "R229"
}
},
{
"type": "way",
"id": 64887990,
"nodes": [
795320324,
1922546679,
1922546572,
1922546692,
2673934802,
768053040,
768053041,
768053043,
768053044,
791492493
],
"tags": {
"highway": "secondary",
"maxspeed": "60",
"name": "Port Road",
"oneway": "no",
"ref": "R229"
}
}
]
}
答案 0 :(得分:3)
您正试图从element
获得最大速度,但它不存在。它位于tags
中的element
对象内。
你需要这样的东西
if (!element.isNull("tags")) {
JSONObject tags = element.getJSONObject("tags");
String maxspeed = tags.getString("maxspeed");
txtSpeed.setText(maxspeed+" here");
} else {
//Your error handling here...
}
答案 1 :(得分:2)
String maxspeed = element.getString("maxspeed");
到
String maxspeed = element.getJSONObject("tags").getString("maxspeed");