Class InclusionFilter

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

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

Example of node specification:

  • "a,b(c,d)" - Includes only the top-level elements a and sub-elements c and d inside b.
  • "x(y)" - Includes only x.y but keeps other elements in x.

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

Author:
Hideki Ikeda
  • Constructor Details

    • InclusionFilter

      public InclusionFilter()
  • Method Details

    • apply

      public com.google.gson.JsonElement apply(com.google.gson.JsonElement source, String nodes)
      Creates a JSON element by extracting JSON elements from the given JSON element based on the nodes string. The nodes are provided as a comma-separated string, where each node defines a portion of the JSON structure to include in 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 include the top-level element a and the element b with only the c and d sub-nodes.

      Examples:

      Example 1: For a flat JSON object

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

      Example 2: For a nested JSON object

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

      Example 3: For nested arrays

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

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

      Specified by:
      apply in interface Filter
      Parameters:
      source - The source JSON element to filter, which should be either a JSON object or an array.
      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.