Pho*_*reo 12 java json jsonpath
题:
我有一个服务,它接受一个JSON字符串作为输入.该JSON模式的每一个地方有些领域并不总是存在的时间是不同的.如何在使用Jayway JsonPath时查询这些字段的值?
我尝试过的:
我使用了Option.DEFAULT_PATH_LEAF_TO_NULLJayway的自述页面解释
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果找不到路径,这应该JsonPath.read()返回null,但是我的代码仍会抛出:
com.jayway.jsonpath.PathNotFoundException:路径$ ['somepath']中缺少属性
当我给它一条不存在的道路时.有谁知道这可能导致什么?
我意识到我做错了什么.该DEFAULT_PATH_LEAF_TO_NULL选项仅处理叶节点.例如:
示例Json
{
"foo":{
"bar":"value"
}
}
Run Code Online (Sandbox Code Playgroud)
如果$.foo.tmp被查询,JsonPath将返回,null因为tmp被假定为叶节点.
如果$.tmp.tmp2被查询,JsonPath将抛出一个
com.jayway.jsonpath.PathNotFoundException,因为tmp不是叶子而且不存在.
为了绕过这个,人们应该使用Option.SUPPRESS_EXCEPTIONS.
| 归档时间: |
|
| 查看次数: |
6674 次 |
| 最近记录: |