【问题标题】:Compare list of JSONArray in ArrayList比较 ArrayList 中 JSONArray 的列表
【发布时间】:2017-06-08 06:51:48
【问题描述】:

我有一个ArrayList,其中包含JSONArrays 的列表

staffArray = new ArrayList<JSONArray>();

JSONArray 的形式如下:

[
    {
      "id": "k40dn-dff02-mm1",
      "name": "staff1",
      "tel": "0123456789",
    },
    {
      "id": "ch2mq-pmw01-ps6",
      "name": "staff2",
      "tel": "9876543210",
    }
    ...
]

ArrayList 将包含不同大小的JSONArray。 现在我想检查每个JSONArrayArrayList,如果它们包含相同的“id”值。所以说,如果ArrayList 有三种不同大小的JSONArray,我怎么知道它们每个都包含一个JSONObject,其中的“id”值相同。

到目前为止,我已经尝试过这个来提取字符串:

for(int i = 0; i < staffArray.size(); i++){
    JSONArray jsonArray = new JSONArray();
    jsonArray = staffArray.get(i);
    for(int j = 0; j < jsonArray.length(); j ++){
        JSONObject json = null;
        try {
            json = jsonArray.getJSONObject(j);
            String id = json.getString("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

【问题讨论】:

    标签: java android json arraylist


    【解决方案1】:

    如果您想检查 ArrayList 中的重复 ID,您可以执行以下操作:

    ArrayList<JSONArray> staffArray = new ArrayList<>();
    
    Set<String> ids = new HashSet<>();
    for (JSONArray array : staffArray) {
        for (int i = 0; i < array.length(); i++) {
            JSONObject obj = array.getJSONObject(i);
            if (!ids.add(obj.getString("id"))) {
                // duplicate IDs found, do something
            }
        }
    }
    

    【讨论】:

    • 感谢您的回复,我想要的是在不同的JSONArrays中找到重复的,说ArrayList包含三个JSONArrays并检查每个JSONArray是否有一个具有相同值的键“id”
    • @JerryKo 我明白了。然后,您只需将 ID 的Set 移到外循环之外。请参阅我编辑的答案。
    【解决方案2】:

    如何使用 group by 对具有相同 id 的 json 数组进行分组

    public static void groupById(List<JSONArray> staffArray) {
        Map<String, List<JSONArray>> jsonArraysById = staffArray.stream().collect(Collectors.groupingBy(jsonArray -> getIdFromJsonArray(jsonArray)));
        jsonArraysById.forEach((id, arrays) -> {
            System.out.println("Arrays with id " + id + " are " + arrays);
        });
    }
    
    public static String getIdFromJsonArray(JSONArray jsonArray) {
        String result = null;
        for (int j = 0; j < jsonArray.length(); j++) {
            JSONObject json = null;
            try {
                json = jsonArray.getJSONObject(j);
                result = json.getString("id");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    
        return result;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 2018-03-02
      • 1970-01-01
      相关资源
      最近更新 更多