jsonArray 判断其中的jsonObject某个属性是否有重复值
要判断jsonArray中的jsonObject某个属性是否有重复值,可以使用HashSet来实现。
首先,创建一个HashSet对象,用于存储已经出现过的属性值。
然后,遍历jsonArray中的每个jsonObject,获取到需要判断的属性值,并将其添加到HashSet中。
在添加之前,可以使用contains方法来判断HashSet中是否已经存在相同的属性值,如果存在则表示有重复值。
以下是使用Java代码实现的示例:
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
// 示例的jsonArray
JSONArray jsonArray = new JSONArray();
jsonArray.put(new JSONObject("{\"name\":\"Alice\",\"age\":20}"));
jsonArray.put(new JSONObject("{\"name\":\"Bob\",\"age\":25}"));
jsonArray.put(new JSONObject("{\"name\":\"Charlie\",\"age\":30}"));
jsonArray.put(new JSONObject("{\"name\":\"Alice\",\"age\":35}"));
// 需要判断的属性名
String propertyName = "name";
// 使用HashSet来存储已经出现过的属性值
HashSet<String> set = new HashSet<>();
// 遍历jsonArray中的每个jsonObject
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// 获取需要判断的属性值
String propertyValue = jsonObject.getString(propertyName);
// 如果HashSet中已经存在相同的属性值,则表示有重复值
if (set.contains(propertyValue)) {
System.out.println("属性值重复:" + propertyValue);
} else {
// 否则,将属性值添加到HashSet中
set.add(propertyValue);
}
}
}
}
在上述示例中,jsonArray中的第一个和第四个jsonObject都具有相同的"name"属性值"Alice",所以会输出"属性值重复:Alice"
原文地址: http://www.cveoy.top/t/topic/iU9X 著作权归作者所有。请勿转载和采集!