问题:
我有一个服务,它以JSON
字符串作为输入。每次JSON
模式都不同,其中某些字段并不总是存在。当这些字段存在时,如何使用Jayway的JsonPath
查询这些字段的值?
我尝试过的:
我使用了Jayway的自述页面中解释的Option.DEFAULT_PATH_LEAF_TO_NULL
。
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: Missing property in path $['somepath']
当我给它一个不存在的路径时。有人知道可能是什么原因吗?
Option.SUPPRESS_EXCEPTIONS
解决了我的问题,这个问题和你的类似。 - VAIBHAV GOUR