要判断 JSON 数组中对象某个属性是否有重复值,可以使用 HashSet 来实现。

首先,创建一个 HashSet 对象,用于存储已经出现过的属性值。

然后,遍历 JSON 数组中的每个对象,获取到需要判断的属性值,并将其添加到 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) {
        // 示例的 JSON 数组
        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<>();

        // 遍历 JSON 数组中的每个对象
        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);
            }
        }
    }
}

在上述示例中,JSON 数组中的第一个和第四个对象都具有相同的'name' 属性值'Alice',所以会输出'属性值重复:Alice'。

如何判断 JSON 数组中对象属性是否重复

原文地址: http://www.cveoy.top/t/topic/qA8S 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录