你好,我正试图从JSON对象中获取距离
{
"destination_addresses": [
"Rabat, Morocco"
],
"origin_addresses": [
"Marrakesh, Morocco"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "324 km",
"value": 323624
},
"duration": {
"text": "3 hours 24 mins",
"value": 12233
},
"status": "OK"
}
]
}
],
"status": "OK"
}
我成功获得了元素对象,但我无法获得距离
org.json.JSONException:没有距离值 at org.json.JSONObject.get(JSONObject.java:389) at com.application.zarbagaskazay.colivoiturage.testMApsActivity $ 1.onResponse(testMApsActivity.java:66) at com.application.zarbagaskazay.colivoiturage.testMApsActivity $ 1.onResponse(testMApsActivity.java:56) 在com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
这是代码
public void onResponse(JSONObject response) {
try {
JSONArray rows = response.getJSONArray("rows");
JSONObject elements=rows.getJSONObject(0);
// JSONObject cc= elements.getJSONObject("distance");
System.out.println(elements.get("distance"));
button.setText(elements.get("distance").toString());
} catch (JSONException e) {
e.printStackTrace();
}
答案 0 :(得分:0)
在我的建议中:
您可以替换
的System.out.println(elements.get( “距离”));
带
<强>的System.out.println(elements.getJSONArray( “元素”)。getJSONObject(0).getJSONObj ECT( “距离”)); 强>
高于sop将打印/提取“距离”json值。
{“text”:“324 km”,“value”:323624}
希望它也适合你!
答案 1 :(得分:0)
JSONObject jsonObject = new JSONObject("YOUR RESPONSE STRING");
JSONArray jsonArray = jsonObject.getJsonArray("rows");
JSONArray jsonArray_elements =jsonArray.getJsonObject(0).getJsonArray("elements");
JSONObject jsonObject_distance =
jsonArray_elements.get(0).getJsonObject("distance");
String text = jsonObject_distance.getString("text");
String value = jsonObject_distance.getString("value");