2017-03-11 45 views
1

我目前遇到以下问题:使用其他JSON对象筛选键和值的JSON

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

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

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

回答

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; 
    } 
+0

我的方法**的return语句必须为Map >',其中String为文件名。有答案吗?我是这样使用JSON的绝对初学者,所以这会很有帮助;) –

+0

@DennisvanderVeeke每个JsonObject都有多个'Entry ','String'是一个键和'JsonElement' a值。 'Entry '代表什么?如果'JsonObject'是与路径关联的json对象,那么'Long'代表什么? – niklabaz

+0

它代表最后修改时间。这可以通过'file.lastModified()' –