gpt4 book ai didi

java - 比较 ArrayList 中的 JSONArray 列表

转载 作者:行者123 更新时间:2023-12-02 12:56:14 27 4
gpt4 key购买 nike

我有一个包含 JSONArray 列表的 ArrayList

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

最佳答案

如果您想检查 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
}
}
}

关于java - 比较 ArrayList 中的 JSONArray 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44428611/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com