【问题标题】:Filter JSONObject in JSONArray Android在 JSONArray Android 中过滤 JSONObject
【发布时间】:2013-01-15 08:09:53
【问题描述】:

我如何过滤 JSONObject“名称”包含“abcd”的 JSONArray

{
    "items":[{
            "id":"082111",
            "name":"abcd efgh"
        }, {
            "id":"082112",
            "name":"abcd klmn"
        }, {
            "id":"082113",
            "name":"klmn efgh"
        }, {
            "id":"082114",
            "name":"abcd efgh"
        }, {
            "id":"082115",
            "name":"efgh oprs"
        }
    ]
}

结果一定是

{
    "items":[{
            "id":"082111",
            "name":"abcd efgh"
        }, {
            "id":"082112",
            "name":"abcd klmn"
        }, {
            "id":"082114",
            "name":"abcd efgh"
        }
    ]
}

我怎样才能得到这样的结果? 我是否应该将 JSONArray 转换为 ArrayList,并在转换为 ArrayList 时进行过滤,然后再次转换为 JSONArray? 如果是,我如何将 JSONArray 转换为 ArrayList 并过滤它?并再次转换为 JSONArray? 请给我示例代码。

【问题讨论】:

  • 有很多教程来实现这样的事情。到目前为止,您尝试过什么?

标签: android json arraylist arrays


【解决方案1】:

使用以下代码,您将获得所需的内容,即如您所说的以字母 abcd 开头。

            JSONObject json = new JSONObject(jsonString);
            JSONArray jData = json.getJSONArray("items");
            for (int i = 0; i < jData.length(); i++) {
                JSONObject jo = jData.getJSONObject(i);

                if ((jo.getString("name")).startsWith("abcd", 0)) {

                    Log.i("Name is ", jo.getString("name"));

                }

            }

【讨论】:

  • iOS中会不会有类似“filteredArrayUsingPredicate”的函数或者不使用for循环?如果json数组包含10'000个对象,for-loop方法会不会太慢??
  • 我认为在 iOS 中您也可以使用 startsWith() 检索您可以检查 iOS 中的方法。我不知道 iOS。
  • 抱歉误导。我的意思是在 Android 中,如果我使用“for-loop”方法对许多 JSONObject 进行过滤,它会拖累 android 设备的性能吗?如果是,那么您有更好的建议吗?非常感谢您的回复。
  • 如果您想获得最佳性能,您可以使用 gson 或 Jakson 解析来满足您的需求。有关解析 json 数据的有效方法的更多信息refer this
猜你喜欢
  • 1970-01-01
  • 2011-05-27
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 2016-01-12
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多