【发布时间】:2017-08-02 01:17:03
【问题描述】:
我目前遇到以下问题:
我希望遍历一组 JSON 文件。我想过滤掉某些与过滤器匹配的 JSON 文件。此过滤器是另一个 JSON 对象。
MongoDB 能够做到这一点;你给一个 JSON 对象作为参数,它会列出包含给定 JSON 元素的文档。
我需要一个平面文件版本,但我无法成功。我使用 GSON 作为我的 JSON 库。
【问题讨论】:
我目前遇到以下问题:
我希望遍历一组 JSON 文件。我想过滤掉某些与过滤器匹配的 JSON 文件。此过滤器是另一个 JSON 对象。
MongoDB 能够做到这一点;你给一个 JSON 对象作为参数,它会列出包含给定 JSON 元素的文档。
我需要一个平面文件版本,但我无法成功。我使用 GSON 作为我的 JSON 库。
【问题讨论】:
使用一个文件路径数组,每个文件路径都包含一个 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<String, Entry<JsonObject, Long>>,字符串是文件名。对此有答案吗?我是这样使用 JSON 的绝对初学者,所以这会很有帮助;)
JsonObject 都有多个Entry<String, JsonElement>,其中String 是一个键,JsonElement 是一个值。 Entry<JsonObject, Long> 代表什么?如果 JsonObject 是与路径关联的 json 对象,那么 Long 代表什么?
file.lastModified() 轻松访问
final Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path)))) 与 jsonParser.parse(reader).getAsJsonObject() 一起更便宜,因为 @987654334 中的一些性能成本@.