Package org.czeal.jsonfilter
Class InclusionFilter
java.lang.Object
org.czeal.jsonfilter.InclusionFilter
- All Implemented Interfaces:
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 elementsa
and sub-elementsc
andd
insideb
."x(y)"
- Includes onlyx.y
but 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 -
Method Summary
-
Constructor Details
-
InclusionFilter
public InclusionFilter()
-
-
Method Details
-
apply
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 elementa
and the elementb
with only thec
andd
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 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
JsonElement
instance built by filtering thesource
based on the givennodes
. - Throws:
IllegalArgumentException
- If the source JSON element is an invalid JSON element.
-