Dennis van der Veeke Dennis van der Veeke - 9 months ago 25
Java Question

Filter JSON for keys & values using other JSON objects

I'm currently having the following issue:

I wish to loop through a set of JSON files. I want to filter out certain JSON files that match a filter. This filter is another JSON object.

MongoDB is able to do this; you give a JSON object as parameter and it will list documents containing the given JSON elements.

I need a flatfile version of this, but I am not able to succeed.

I'm using GSON as my JSON library.

Any help is greatly appriciated.

Answer Source

Requires Consumes an array of file paths that each contain a JSON string, and a JsonObject that represents the filtering rules. Returns a list of file paths that match the filtering rules.

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 String raw = FileUtils.readFileToString(new File(path));
            final JsonObject file = new Gson().fromJson(raw, JsonObject.class);
            final Set<Map.Entry<String, JsonElement>> fileEntries = file.entrySet();
            if (fileEntries.containsAll(rulesEntries)) filtered.add(path);
        return filtered;