我试图在评估 JSON 路径时抑制所有异常。但是当我将 JSON 路径库升级到 2.7 时,它似乎没有按预期工作。例如:
var node = objectMapper.readTree("{\"test\" : null}");
JsonPath.using(Configuration.builder()
.options(Option.SUPPRESS_EXCEPTIONS).build())
.parse(node)
.read("$.test[?(@ != null)]");
我们抛出了一个异常。
Filter: [?] can not be applied to primitives. Current context is: null
com.jayway.jsonpath.InvalidPathException: Filter: [?] can not be applied to primitives. Current context is: null
在旧版本 - 2.6 中,evaluate 方法已经用 try/catch 包裹,但 2.7 没有。 这可能是根本原因。
public <T> T read(Object jsonObject, Configuration configuration) {
boolean optAsPathList = configuration.containsOption(AS_PATH_LIST);
boolean optAlwaysReturnList = configuration.containsOption(Option.ALWAYS_RETURN_LIST);
boolean optSuppressExceptions = configuration.containsOption(Option.SUPPRESS_EXCEPTIONS);
try {
if (path.isFunctionPath()) {
if (optAsPathList || optAlwaysReturnList) {
throw new JsonPathException("Options " + AS_PATH_LIST + " and " + ALWAYS_RETURN_LIST + " are not allowed when using path functions!");
}
return path.evaluate(jsonObject, jsonObject, configuration).getValue(true);
} else if (optAsPathList) {
return (T) path.evaluate(jsonObject, jsonObject, configuration).getPath();
} else {
Object res = path.evaluate(jsonObject, jsonObject, configuration).getValue(false);
if (optAlwaysReturnList && path.isDefinite()) {
Object array = configuration.jsonProvider().createArray();
configuration.jsonProvider().setArrayIndex(array, 0, res);
return (T) array;
} else {
return (T) res;
}
}
} catch (RuntimeException e) {
if (!optSuppressExceptions) {
throw e;
} else {
if (optAsPathList) {
return (T) configuration.jsonProvider().createArray();
} else {
if (optAlwaysReturnList) {
return (T) configuration.jsonProvider().createArray();
} else {
return (T) (path.isDefinite() ? null : configuration.jsonProvider().createArray());
}
}
}
}
}