如何在解析无名JSONObject的JSONArray时停止for循环?
我想解析一个JSONArray
,其中包含JSONObject
s,它们没有名称,并且其阵列中的(index
int)位置每周都在更改。我试图通过它的属性来解析特定的Object
,但是我的解析器只返回数组中的最后一个对象。如何在解析无名JSONObject的JSONArray时停止for循环?
当我想要解析并确定对象的int索引以便进一步解析时,如何停止循环。
try { JSONArray jArray = JSONthing.getJSONfromURL("http://something.com");
String attributeiwant = "abc";
for (int i = 0; i < jArray.length(); i++) {
JSONObject alpha = jArray.getJSONObject(i);
String attributeparsed = alpha.getString("widget");
if (attributeparsed == attributeiwant) {
//determine int index of object, so i can parse other attributes
//from same object
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}
回答:
使用String.equals比较,而不是==字符串
try { JSONArray jArray = JSONthing.getJSONfromURL("http://something.com");
String attributeiwant = "abc";
for (int i = 0; i < jArray.length(); i++) {
JSONObject alpha = jArray.getJSONObject(i);
String attributeparsed = alpha.getString("widget");
if (attributeparsed.equals(attributeiwant)) {
//determine int index of object, so i can parse other attributes
//from same object
// Get data from JsonObject
break;
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}
回答:
use break;声明打破循环,改变你的代码如下:
int i = 0; try {
JSONArray jArray = JSONthing.getJSONfromURL("http://something.com");
String attributeiwant = "abc";
for (; i < jArray.length(); i++) {
JSONObject alpha = jArray.getJSONObject(i);
String attributeparsed = alpha.getString("widget");
if (attributeparsed.equals(attributeiwant)) {
//determine int index of object, so i can parse other attributes
//from same object
break;
}
}
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+ e.toString());
}
if(i<jArray.length())
{
//item found, use i as index of object.
}
else
//item not found.
以上是 如何在解析无名JSONObject的JSONArray时停止for循环? 的全部内容, 来源链接: utcz.com/qa/262838.html