所以我在这里有一些代码,我正在尝试进行优化,我无法弄清楚如何将其至少变成for:每个循环。是否有某种Iterator可以让我为Iterator中的每个项目做些什么?任何帮助将不胜感激。
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 :(得分:0)
我确实找到了一种方法来使用for:每个循环,我只需要从使用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));
}