【发布时间】:2015-02-07 09:02:53
【问题描述】:
我正在使用 JSON 对象。它给出了这样的结果
{
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 19.0759817,
"lng" : 80.27071789999999
},
"southwest" : {
"lat" : 12.5100381,
"lng" : 72.8772599
}
},
"copyrights" : "Map data ©2015 Google",
"legs" : [
{
"distance" : {
"text" : "1,334 km",
"value" : 1333618
},
"duration" : {
"text" : "17 hours 43 mins",
"value" : 63763
},
"end_address" : "Mumbai, Maharashtra, India",
"end_location" : {
"lat" : 19.0759817,
"lng" : 72.8776544
},
"start_address" : "Chennai, Tamil Nadu, India",
"start_location" : {
"lat" : 13.0826782,
"lng" : 80.27071789999999
},
所以我正在检索以下数组 routes->legs->distance`。使用以下代码
JSONArray one = reader.getJSONArray("routes");
for ( i = 0; i < one.length(); i++) {
two = one.getJSONObject(i);
three = two.getJSONArray("legs");
for ( j = 0; j < three.length(); j++) {
four = three.getJSONObject(j);
bounds = four.getJSONObject("distance");
distance[i]=bounds.getString("text");
它工作正常。有时输入错误时我的 JSON 结果是这样的。
{
"routes" : [],
"status" : "NOT_FOUND"
}
所以当我在这个空的 JSON 对象中搜索腿时,我的 android 应用程序会挂起并自动终止。所以我应该检查我的 JSON 对象中是否存在 legs 数组。
如果在场,我将使用我的代码。否则我只会向用户显示警告消息。
【问题讨论】:
-
可以查看路由数组的长度