【问题标题】:How stop a for loop when parsing a JSONArray for nameless JSONObject?解析无名 JSONObject 的 JSONArray 时如何停止 for 循环?
【发布时间】:2012-07-31 04:36:27
【问题描述】:

我想解析一个JSONArray,其中包含没有名称的JSONObjects,并且数组中的(index int)位置每周左右变化。我试图通过它的属性解析特定的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());
        }

【问题讨论】:

    标签: android json parsing for-loop


    【解决方案1】:

    使用 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());
            }
    

    【讨论】:

      【解决方案2】:

      使用中断;打破循环的语句,将您的代码更改为:

      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.
      

      【讨论】:

        猜你喜欢
        • 2019-05-16
        • 1970-01-01
        • 2021-05-09
        • 2014-05-12
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 2021-07-25
        • 1970-01-01
        相关资源
        最近更新 更多