如何通过应用JSONPath表达式从Java对象而不是JSON字符串中获取值?
我收到了从JSON字符串创建的Java对象(通过Jackson,无法影响它):
public class MyJSONInputClass {
private String foo;
private int[] bar = { 1, 5, 9 };
private OtherClass baz;
....
}
我还具有一些JSONPath表达式,例如反映对象中值的Java字符串(它们可能要复杂得多):
"$.foo"
"$.bar[5]"
"$.baz.someProperty"
我想使用生成的java对象(解组后为MyJSONInputClass的实例)解析这些表达式:
public Object resolve(MyJSONInputClass input, String expression) {
...
}
我用ObjectMapper
从杰克逊创建一个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>
一些注意事项:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句