我的JSON
{
"destination_addresses" : [
"11/6, Dhandapani St, VGP Seethapathy Nagar, Velachery, Chennai, Tamil Nadu 600042, India"
],
"origin_addresses" : [ "Magazine Road, St Thomas Mount, Chennai, Tamil Nadu 600016, India" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "6.6 km",
"value" : 6589
},
"duration" : {
"text" : "21 mins",
"value" : 1268
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
我需要从此JSON获取距离值。
我一直在获取价值直到行,但是在尝试将此JSON对象转换为JSON数组时遇到异常。
成功直至此
JSONArray rows= (JSONArray) jsonObject.get("rows");
JSONObject elements= (JSONObject) rows.get(0);
Log.d("Eleemnrs",String.valueOf(elements));
当我执行以下代码时,距离没有价值
JSONArray rows= (JSONArray) jsonObject.get("rows");
JSONObject elements= (JSONObject) rows.get(0);
elements.get("distance");
Log.d("Eleemnrs",String.valueOf(elements));
答案 0 :(得分:1)
JSONObject elements =(JSONObject)rows.get(0); 结果元素为:
{
"elements" : [
{
"distance" : {
"text" : "10.3 km",
"value" : 10320
},
"duration" : {
"text" : "20 mins",
"value" : 1178
},
"status" : "OK"
}
]
}
如果您应该获取distance
值,则应首先get("elements")
,然后获取getJsonObject(0).get(“ distance”)
答案 1 :(得分:0)
当您执行elements.get(“ distance”)
时,您没有使用该对象。JSONArray rows= (JSONArray) jsonObject.get("rows");
JSONObject elements= (JSONObject) rows.get(0);
//Here you are not assigning the distance object to any variable. It is simply discarded
elements.get("distance");
Log.d("Eleemnts",String.valueOf(elements));
您可以按以下方式修改代码,以将距离对象放入JsonObject并从中读取所需的值。
JSONArray rows= (JSONArray) jsonObject.get("rows");
JSONObject elements= (JSONObject) rows.get(0);
JsonObject distance = elements.get("distance");
Log.d("Distance text is ", distance.getString("text"));
Log.d("Distance value is ", distance.getInt("value"));
答案 2 :(得分:0)
JSONArray rows= (JSONArray) jsonObject.get("rows");
JSONObject elements= (JSONObject) rows.get(0);
JSONArray one= (JSONArray) elements.get("elements");
JSONObject two=(JSONObject)one.get(0);
JSONObject three=(JSONObject)two.get("distance");
int finalvalue= (int) three.get("value");
确定答案!