Class ExclusionFilter

java.lang.Object
org.czeal.jsonfilter.ExclusionFilter
All Implemented Interfaces:
Filter

public class ExclusionFilter extends Object implements Filter
A filter implementation that excludes specified JSON elements from a given JSON element. The exclusion rules are defined using a comma-separated string where nested fields can be specified using parentheses.

Example of node specification:

  • "a,b(c,d)" - Excludes top-level elements a and sub-elements c and d inside b.
  • "x(y)" - Excludes the sub-element y inside x, while keeping other elements in x.

If the input JSON is a primitive value or null, it is returned as is.

Author:
Hideki Ikeda
  • Constructor Details

    • ExclusionFilter

      public ExclusionFilter()
  • Method Details

    • apply

      public com.google.gson.JsonElement apply(com.google.gson.JsonElement source, String nodes)
      Creates a JSON element by excluding JSON elements from the given JSON element based on the nodes string. The nodes string is provided as a comma-separated string, where each node defines a portion of the JSON structure to exclude from the result. Nested fields can be specified using parentheses. For example, a nodes string might be "a,b(c,d)", indicating that the output should not include the top-level element a and sub-elements c and d inside b.

      Examples:

      Example 1: For a flat JSON object

       JsonElement jsonElement = JsonParser.parseString("{\"a\":1,\"b\":2,\"c\":3}");
      
       JsonElement filtered = new ExclusionFilter().apply(jsonElement, "a,b");
      
       System.out.println(filtered); // {"c":3}
       

      Example 2: For a nested JSON object

       JsonElement jsonElement = JsonParser.parseString("{\"x\":{\"y\":{\"z\":5},\"w\":10},\"v\":20}");
      
       JsonElement filtered = new ExclusionFilter().apply(jsonElement, "x(y)");
      
       System.out.println(filtered); // {"x":{"w":10},"v":20}
       

      Example 3: For nested arrays

       JsonElement jsonElement = JsonParser.parseString("[[[{\"name\":\"john\",\"type\":0}]]]");
      
       JsonElement filtered = new ExclusionFilter().apply(jsonElement, "name");
      
       System.out.println(filtered); // [[[{"type":0}]]]
       

      If the source JSON is a primitive or null, filtering is not applicable and the deep copy of the source is returned unmodified.

      Invoking this method is equivalent to invoking filter(JsonElement, Node) (source, new NodeParser.parse(nodes)).

      Specified by:
      apply in interface Filter
      Parameters:
      source - The source JSON element to filter.
      nodes - A comma-separated string defining allowed JSON nodes to include. Each node can specify nested fields using parentheses.
      Returns:
      A new JsonElement instance built by filtering the source based on the given nodes.
      Throws:
      IllegalArgumentException - If the source JSON element is an invalid JSON element.