问题:
我有一个接受JSON字符串作为输入的服务。每次出现某些字段时,JSON模式都是不同的。当这些字段存在时,我如何使用Jayway的JsonPath查询这些字段的值?
我尝试过的:
我用Option.DEFAULT_PATH_LEAF_TO_NULL作为Jayway的自述页面解释
Configuration config = Configuration.defaultConfiguration()
.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);
if (JsonPath.isPathDefinite(attribute.jsonPath))
{
String value = JsonPath.using(config).parse(currentTx).read(attribute.jsonPath);
if (value != null)
{
attributeValues.add(value);
}
}
else
{
List<String> attributeValuesArray = JsonPath.using(config).parse(currentTx).read(attribute.jsonPath);
for (String value : attributeValuesArray)
{
if (value != null)
{
attributeValues.add(value);
}
}
}如果找不到路径,这将使JsonPath.read()返回null,但是我的代码仍然抛出:
com.jayway.jsonpath.PathNotFoundException:路径$'somepath‘中缺少的属性
当我给它一条不存在的路。有人知道是什么导致了这一切吗?
发布于 2016-07-19 04:22:05
我意识到我做错了什么。DEFAULT_PATH_LEAF_TO_NULL选项只处理叶节点。例如:
样本Json
{
"foo":{
"bar":"value"
}
}如果查询$.foo.tmp,JsonPath将返回null,因为tmp应该是叶节点。
如果查询$.tmp.tmp2,JsonPath将抛出一个
com.jayway.jsonpath.PathNotFoundException作为tmp不是叶子,也不存在。
为了绕过这个问题,我们应该使用Option.SUPPRESS_EXCEPTIONS。
https://stackoverflow.com/questions/38449267
复制相似问题