【问题标题】:Android: Getting elements from a JSONArray without using standard for loopAndroid:从 JSONArray 获取元素而不使用标准 for 循环
【发布时间】:2013-11-21 01:29:35
【问题描述】:

因此,我在这里有一些代码正在尝试优化,但我无法弄清楚如何将其至少放入 for:each 循环中。是否有某种迭代器可以让我对迭代器中的每个项目进行处理?任何帮助将不胜感激。

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;
}

}

【问题讨论】:

  • 为什么要优化这么多?我会想如果有任何东西将 JSONObject json 从 for 循环中拉出来(那么你只有一个内存分配)会比尝试优化 for 循环更好的开始

标签: java android arraylist arrays jsonobject


【解决方案1】:

我确实找到了使用 for:each 循环的方法,我只需要从使用 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));
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-31
    • 2021-07-31
    • 2021-12-07
    • 2014-09-29
    • 2020-03-06
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    相关资源
    最近更新 更多