2013-11-21 60 views
0

所以我在這裏有一些代碼,我試圖優化,我無法弄清楚如何使它至少成爲for:each循環。有沒有我可以使用的某種迭代器,可以讓我爲迭代器中的每個項目執行操作?任何幫助將不勝感激。Android:從JSONArray獲取元素而不使用標準for循環

public static ArrayList<Community> parseRelatedCommunities(String response) throws JSONException { 

    ArrayList<Community> relCommunities = new ArrayList<Community>(); 
    Log.d(TAG, "parseRelatedCommunities:"); 
    try { 
     Gson gson = new Gson(); 
     int size; 
     JSONObject responseObj = new JSONObject(response); 
     responseObj = responseObj.getJSONObject(JSON_RESPONSE); 
     JSONArray communitiesArray = responseObj.getJSONArray(JSON_COMMUNITY); 
     Log.d(TAG, "parsing communities: " + communitiesArray.toString()); 
     size = communitiesArray.length(); 
      //this needs to change 
      for(int i=0; i<size; i++) { 
       JSONObject json = communitiesArray.getJSONObject(i); 
       relCommunities.add(gson.fromJson(json.toString(), Community.class));} 
     gson = null; 
    } 
    catch (JSONException e) 
    { 
     Log.d(TAG, "JSON Parse Related Communities error: " + e.getStackTrace().toString()); 

    } 
    finally 
    { 
     if(relCommunities.size() <= 0) 
     { 
     Community noCommunities = new Community(); 
     noCommunities.name = "No Available Communities"; 
     relCommunities.add(noCommunities); 
     } 
    } 
    return relCommunities; 
} 

}

+0

爲什麼你需要優化它這麼多?我會想,如果有任何東西從for循環中拉出JSONObject json(然後你只有一個內存分配)比嘗試優化for循環更好的開始 – panini

回答

0

我沒有找到一個方法來使用的:每一個循環,我不得不使用JSONArrays和一個JSONObjects到JsonArrays和JsonElements(注意情況的細微差別)開關。這裏是更新的解析部分:

JsonObject object = parser.parse(readerJS).getAsJsonObject(); 

     JsonObject responseObject = object.getAsJsonObject("response"); 

     JsonArray categoriesArray = responseObject.getAsJsonArray("badges"); 

     for (JsonElement je : categoriesArray) { 
      newGameData.categories.add(gs.fromJson(je, CategoryData.class)); 
     }