我正在尝试通过以下网址(插入“我的API密钥”的地方)从google maps API访问一些JSON信息。
Month_name CASH/TPA Total
April CASH 2184074.0
August CASH 1780238.0
December CASH 1176889.0
但是,每当我尝试访问数据时,我都会收到一些JSON错误。
数据采用以下格式:
https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=-37.8136,144.9631&destinations=-37.811363%2c144.936967&key=MY_API_KEY
我专门尝试使用以下代码访问持续时间的“值”区域:
{
"destination_addresses" : [ "123 Swanston St, Melbourne VIC 3000, Australia" ],
"origin_addresses" : [ "350 Bourke St, Melbourne VIC 3000, Australia" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1.1 km",
"value" : 1051
},
"duration" : {
"text" : "7 mins",
"value" : 399
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
代码进入“获取传递的元素”,然后使用以下stackTrace引发JSON异常:
try {
URL url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=-37.8136,144.9631&destinations=-37.811363%2c144.936967&key=MY_API_KEY");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONObject alldata = new JSONObject(data);
JSONArray rows = alldata.getJSONArray("rows");
Log.v("Log","Gets passed rows");
JSONObject elements = rows.getJSONObject(0);
Log.v("Log","Gets passed elements");
JSONObject duration = elements.getJSONObject("duration");
Log.v("Log","Gets passed duration");
JSONObject value = duration.getJSONObject("value");
我也不可能将elemenmts作为JSONArray获得,因为每当执行此操作时,它就会告诉我数组超出范围。
我如何访问持续时间的值?