如何通过应用 JSONPath 表达式从 Java 对象而不是 JSON 字符串获取值?
我收到一个从 JSON 字符串创建的 Java 对象(通过 Jackson,无法影响它):
public class MyJSONInputClass {
private String foo;
private int[] bar = { 1, 5, 9 };
private OtherClass baz;
....
}
我还有一些 JSONPath 表达式作为反射(reflect)对象中值的 Java 字符串(它们可能要复杂得多):
"$.foo"
"$.bar[5]"
"$.baz.someProperty"
我想使用生成的 java 对象(解码后的 MyJSONInputClass 实例)解析这些表达式:
public Object resolve(MyJSONInputClass input, String expression) {
...
}
最佳答案
我使用 ObjectMapper
来自 Jackson创建一个 Map<String, Object>
来自给定的 Java 对象(包含其他不能作为原始类型解析的属性映射)。那么JSONPath可以读取它并对表达式求值。
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;
}
要包含的依赖项:
<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>
一些注意事项:
- 适用于分层对象。
- 未针对循环结构进行测试。
关于java - Java 对象的 JSONPath 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27743693/