JSONPath resolver for Java objects JSONPath resolver for Java objects json json

JSONPath resolver for Java objects


I use ObjectMapper from Jackson to create a Map<String, Object> from the given Java object (containing other maps for properties not parseable as primitive types). Then JSONPath can read it and evaluate the expression.

public Object resolve(Object input, String expression) {    // Get the mapper with default config.    ObjectMapper mapper = new ObjectMapper();    // Make the object traversable by JSONPath.    Map<String, Object> mappedObject = mapper.convertValue(input, Map.class);    // Evaluate that expression    Object output = JsonPath.read(mappedObject, expression);    return output;}

Dependencies to include:

<dependency>    <groupId>com.jayway.jsonpath</groupId>    <artifactId>json-path</artifactId>    <version>1.2.0</version></dependency><dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-databind</artifactId>    <version>2.4.4</version></dependency>

Some notes:

  • Works for hierarchical objects.
  • Not tested for circular structures.


Aren't we adding a little overhead of converting to map, instead we could use JXPath library directly on Java Objects