Package org.czeal.jsonfilter
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 elementsaand sub-elementscanddinsideb."x(y)"- Includes onlyx.ybut keeps other elements inx.
If the input JSON is a primitive value or
null, it is returned as is.- Author:
- Hideki Ikeda
-
-
Constructor Summary
Constructors Constructor Description InclusionFilter()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description com.google.gson.JsonElementapply(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.
-
-
-
Method Detail
-
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 elementaand the elementbwith only thecanddsub-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:
applyin interfaceFilter- 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
JsonElementinstance built by filtering thesourcebased on the givennodes. - Throws:
IllegalArgumentException- If the source JSON element is an invalid JSON element.
-
-