[英]parsing json 2 arrays (embbeded ) in android
我试图在jsonObject distance (10194)中找到值
{
"destination_addresses" : [ "Burnaby, BC, Canada" ],
"origin_addresses" : [ "Vancouver, BC, Canada" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "10.2 km",
"value" : 10194
},
"duration" : {
"text" : "19 mins",
"value" : 1118
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
我写了这段代码,但它给了我null
rows = jObj.getJSONObject(TAG_ROWS);
JSONArray elements = new JSONArray (rows.getString(TAG_ELEMENTS));
for (int i=0; i<elements.length();i++){
JSONObject obj = elements.optJSONObject(i);
JSONObject distance = obj.getJSONObject(TAG_DISTANCE);
value= distance.getString(TAG_VALUE);
任何想法 ??
根据您的JSON
,即使rows
的类型也为JSONArray
,但是您通过这种方式获取行
rows = jObj.getJSONObject(TAG_ROWS);
因此,这个问题。
您需要像这样获取rows
:
JSONArray rows = jObj.getJSONArray(TAG_ROWS);
对象“行”必须键入JSONArray,因为它包含的是一个数组。 之后,您必须为之做另一个操作并获取另一个为“元素”的数组,然后为第二个数组执行循环。 您必须得到类似的东西:
rows = jObj.getJSONArray(TAG_ROWS);
for (int i=0; i<rows.length();i++){
JSONArray elements = new JSONArray (rows.getString(TAG_ELEMENTS));
for (int j=0; j<elements.length();j++){
JSONObject obj = elements.optJSONObject(j);
JSONObject distance = obj.getJSONObject(TAG_DISTANCE);
value= distance.getString(TAG_VALUE);
}
}
您将必须执行以下操作
try {
JSONObject jsonObj = new JSONObject(YOUR-JSON-STRING-HERE);
String destination = jsonObj.getString("destination_addresses");
// printing the destination and checking wheather parsed correctly
Log.v("Destination", destination);
JSONArray jarRow = jsonObj.getJSONArray("rows");
for(int i=0;i<jarRow.length(); i++){
// creating an object first
JSONObject ElementsObj = jarRow.getJSONObject(i);
// and getting the array out of the object
JSONArray jarElements = ElementsObj.getJSONArray("elements");
for(int j=0; j<jarElements.length(); j++){
JSONObject distanceObj = jarElements.getJSONObject(j).getJSONObject("distance");
String distanceStr = distanceObj.getString("value");
Log.v("finally getting distance : ", distanceStr);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
这是DDMS的屏幕截图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.