这是示例JSON输出:
{
"status": "OK",
"routes": [ {
"summary": "I-40 W",
"legs": [ {
"steps": [ {
"travel_mode": "DRIVING",
"start_location": {
"lat": 41.8507300,
"lng": -87.6512600
},
"end_location": {
"lat": 41.8525800,
"lng": -87.6514100
},
"polyline": {
"points": "a~l~Fjk~uOwHJy@P"
},
"duration": {
"value": 19,
"text": "1 min"
},
"html_instructions": "Head \u003cb\u003enorth\u003c/b\u003e on \u003cb\u003eS Morgan St\u003c/b\u003e toward \u003cb\u003eW Cermak Rd\u003c/b\u003e",
"distance": {
"value": 207,
"text": "0.1 mi"
}
},
...
... additional steps of this leg
...
... additional legs of this route
"duration": {
"value": 74384,
"text": "20 hours 40 mins"
},
"distance": {
"value": 2137146,
"text": "1,328 mi"
},
"start_location": {
"lat": 35.4675602,
"lng": -97.5164276
},
"end_location": {
"lat": 34.0522342,
"lng": -118.2436849
},
"start_address": "Oklahoma City, OK, USA",
"end_address": "Los Angeles, CA, USA"
} ],
"copyrights": "Map data ©2010 Google, Sanborn",
"overview_polyline": {
"points": "a~l~Fjk~uOnzh@vlbBtc~@tsE`vnApw{A`dw@~w\\|tNtqf@l{Yd_Fblh@rxo@b}@xxSfytAblk@xxaBeJxlcBb~t@zbh@jc|Bx}C`rv@rw|@rlhA~dVzeo@vrSnc}Axf]fjz@xfFbw~@dz{A~d{A|zOxbrBbdUvpo@`cFp~xBc`Hk@nurDznmFfwMbwz@bbl@lq~@loPpxq@bw_@v|{CbtY~jGqeMb{iF|n\\~mbDzeVh_Wr|Efc\\x`Ij{kE}mAb~uF{cNd}xBjp]fulBiwJpgg@|kHntyArpb@bijCk_Kv~eGyqTj_|@`uV`k|DcsNdwxAott@r}q@_gc@nu`CnvHx`k@dse@j|p@zpiAp|gEicy@`omFvaErfo@igQxnlApqGze~AsyRzrjAb__@ftyB}pIlo_BflmA~yQftNboWzoAlzp@mz`@|}_@fda@jakEitAn{fB_a]lexClshBtmqAdmY_hLxiZd~XtaBndgC"
},
"warnings": [ ],
"waypoint_order": [ 0, 1 ],
"bounds": {
"southwest": {
"lat": 34.0523600,
"lng": -118.2435600
},
"northeast": {
"lat": 41.8781100,
"lng": -87.6297900
}
}
} ]
}
如何获得距离值?这是我尝试但失败的原因。
jsonObject = new JSONObject(mJsonResults.toString());
JSONArray array = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legs = routes.getJSONArray("legs");
JSONObject steps = legs.getJSONObject(0);
JSONObject distance = steps.getJSONObject("distance");
JSONObject value = distance.getJSONObject("text");
Log.d("Distance", value.toString());
并且logcat没有输出。但是当我尝试Log.d("Distance",distance.toString());
时,我得到的值是D/Distance﹕ {"value":43481,"text":"43.5 km"}
我想要得到的是" text"在里面"距离"。我该怎么办?
我的代码来自另一个JSON数据,但它的格式与上面的JSON示例相同
答案 0 :(得分:0)
您错过了解析JsonArray的步骤并在获取距离方面遇到了一些问题
JSONArray routesArray = jsonObject.getJSONArray("routes");
JSONObject routes = array.getJSONObject(0);
JSONArray legsArray = routes.getJSONArray("legs");
JSONObject legs = legsArray.getJSONObject(0);
JSONArray stepsArray = routes.getJSONArray("steps");
JSONObject steps = stepsArray.getJSONObject(0);
JSONObject distanceObject = steps.getJSONObject("distance");
String text = distance.getString("text");
String value = distance.getString("value");