【发布时间】:2020-01-06 14:52:07
【问题描述】:
我想使用 Google 距离矩阵 API 来获取在两个位置之间旅行所需的持续时间。但是当我尝试从返回的数据(JSON 编码)中获取持续时间时,getJSONArray 方法总是返回 null。
这是 Google 发送的数据:
{
"destination_addresses" : [ "Rome, Metropolitan City of Rome, Italy" ],
"origin_addresses" : [ "Berlin, Germany" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1,501 km",
"value" : 1501458
},
"duration" : {
"text" : "15 hours 5 mins",
"value" : 54291
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
这是获取持续时间的方法:
public static int getDurationFromJSON(String json){
try {
JSONObject jsonObj = new JSONObject(json)
.getJSONArray("rows")
.getJSONObject(0)
.getJSONArray ("elements")
.getJSONObject(0)
.getJSONObject("duration");
return (int)(jsonObj.getInt("value") / 60.0f + 0.5f);
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
getJSONArray("rows") 返回 null。
【问题讨论】:
-
您是否检查从 Google API 收到的数据。 json变量的内容是什么?
-
json变量的数据就是贴出来的json代码。它和我在浏览器中启动请求时得到的完全一样。
-
但是你确定你在调试代码时将相同的内容放入变量“json”吗?
-
我 100% 确定。
-
我建议您使用调试器查看 jsonObj 变量中的内容。如果函数返回 null 表示什么都没有,或者它不是预期的类型,如果你说你对内容很确定,那么你请求的类型是错误的。
标签: java android json nullpointerexception