我们正在使用Google Maps API处理我们在Android Studio中制作的APP。但是我们遇到了阅读JSON文件的问题。我们如何访问所有发送的信息。
JSON File Snippet:
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 56.30786089999999,
"lng" : 9.167680600000001
},
"southwest" : {
"lat" : 56.13854869999999,
"lng" : 8.967453599999999
}
},
"copyrights" : "Kortdata ©2016 Google",
"legs" : [
{
"distance" : {
"text" : "7,6 km",
"value" : 7592
},
更多JSON文件:JOSNFILE
我们需要将所有distance.value相加以计算总距离。到目前为止,我们只知道如何检索第一个距离。请记住,并非所有名为distance的值都相关。
目前我们可以从A到B旅行,但如果我们添加一个航点C,我们只能得到从A到B的距离,而不是从B到C的距离。
段:
private void parseJSon(String data) throws JSONException {
if (data == null)
return;
List<Route> routes = new ArrayList<Route>();
JSONObject jsonData = new JSONObject(data);
JSONArray jsonRoutes = jsonData.getJSONArray("routes");
for (int i = 0; i < jsonRoutes.length(); i++) {
JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
Route route = new Route();
JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
JSONObject jsonLeg = jsonLegs.getJSONObject(0);
JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");
route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));
route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"));
route.endAddress = jsonLeg.getString("end_address");
route.startAddress = jsonLeg.getString("start_address");
route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"));
route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"));
route.points = decodePolyLine(overview_polylineJson.getString("points"));
routes.add(route);
}
listener.onDirectionFinderSuccess(routes);
}