Java 对象的 JSONPath 解析器

Seb*_*rth 6 java reflection json jsonpath jackson

如何通过应用 JSONPath 表达式从 Java 对象而不是从 JSON 字符串获取值?


我收到一个从 JSON 字符串创建的 Java 对象(通过 Jackson,无法影响它):

public class MyJSONInputClass {
    private String foo;
    private int[] bar = { 1, 5, 9 };
    private OtherClass baz;
    ....
}
Run Code Online (Sandbox Code Playgroud)

我进一步有一些 JSONPath 表达式作为 Java 字符串反映对象中的值(它们可能更复杂):

"$.foo"
"$.bar[5]"
"$.baz.someProperty"
Run Code Online (Sandbox Code Playgroud)

我想使用生成的 java 对象(MyJSONInputClass 的实例,解组后)解析这些表达式:

public Object resolve(MyJSONInputClass input, String expression) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

Seb*_*rth 8

我使用JacksonObjectMapper从给定的 Java 对象创建一个(包含不可解析为原始类型的属性的其他映射)。然后JSONPath可以读取它并计算表达式。Map<String, Object>

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;
}
Run Code Online (Sandbox Code Playgroud)

依赖项包括:

<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>
Run Code Online (Sandbox Code Playgroud)

一些注意事项:

  • 适用于分层对象。
  • 未针对圆形结构进行测试。