Package org.czeal.jsonfilter
Class ExclusionFilter
java.lang.Object
org.czeal.jsonfilter.ExclusionFilter
- All Implemented Interfaces:
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 elementsa
and sub-elementsc
andd
insideb
."x(y)"
- Excludes the sub-elementy
insidex
, while keeping 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
-
ExclusionFilter
public ExclusionFilter()
-
-
Method Details
-
apply
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 elementa
and sub-elementsc
andd
insideb
.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 interfaceFilter
- 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 thesource
based on the givennodes
. - Throws:
IllegalArgumentException
- If the source JSON element is an invalid JSON element.
-