1

我想解析一个JSONArray包含JSONObject没有名称的 s 并且其index在数组中的(int)位置每周左右变化的 a。我试图Object通过它的属性来解析一个特定的,但我的解析器只返回数组中的最后一个对象。

当循环到达我要解析的对象并确定对象的 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());
        }
4

2 回答 2

2

使用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());
        }
于 2012-07-31T04:42:12.913 回答
1

使用休息;语句来打破循环,将您的代码更改为以下内容:

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.
于 2012-07-31T04:41:55.533 回答