【问题标题】:Filter JSON for keys & values using other JSON objects使用其他 JSON 对象过滤 JSON 中的键和值
【发布时间】:2017-08-02 01:17:03
【问题描述】:

我目前遇到以下问题:

我希望遍历一组 JSON 文件。我想过滤掉某些与过滤器匹配的 JSON 文件。此过滤器是另一个 JSON 对象。

MongoDB 能够做到这一点;你给一个 JSON 对象作为参数,它会列出包含给定 JSON 元素的文档。

我需要一个平面文件版本,但我无法成功。我使用 GSON 作为我的 JSON 库。

【问题讨论】:

    标签: java json mongodb gson


    【解决方案1】:

    使用一个文件路径数组,每个文件路径都包含一个 JSON 字符串和一个表示过滤规则的 JsonObject。返回与过滤规则匹配的文件路径列表。

    public List<String> filter(String[] filePaths, JsonObject rules) throws FileNotFoundException {
            final List<String> filtered = new ArrayList<String>();
            final Set<Map.Entry<String, JsonElement>> rulesEntries = rules.entrySet();
            for (String path : filePaths) {
                final Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path))));
                final JsonObject file = jsonParser.parse(reader).getAsJsonObject();
                final Set<Map.Entry<String, JsonElement>> fileEntries = file.entrySet();
                if (fileEntries.containsAll(rulesEntries)) filtered.add(path);
            }
            return filtered;
        }
    

    【讨论】:

    • 我的方法的返回语句必须Map&lt;String, Entry&lt;JsonObject, Long&gt;&gt;,字符串是文件名。对此有答案吗?我是这样使用 JSON 的绝对初学者,所以这会很有帮助;)
    • @DennisvanderVeeke 每个JsonObject 都有多个Entry&lt;String, JsonElement&gt;,其中String 是一个键,JsonElement 是一个值。 Entry&lt;JsonObject, Long&gt; 代表什么?如果 JsonObject 是与路径关联的 json 对象,那么 Long 代表什么?
    • 表示上次修改时间。可以通过file.lastModified() 轻松访问
    • 好的,我已经修复了它,虽然我注意到你的代码中有一个错误。您偶然创建了两次规则的条目集,并且在 if 语句中,您比较了这两个条目集,它们显然是相同的,所以它总是返回 true。从文件变量而不是规则创建第二个(在 if 语句之上)条目集,然后它就可以工作了。非常感谢!
    • @niklabaz 添加第 3 方库并累积要解析为字符串的值可能过于昂贵:传递 final Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path))))jsonParser.parse(reader).getAsJsonObject() 一起更便宜,因为 @987654334 中的一些性能成本@.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多