使用Jayway的可选JsonPath

时间:2016-07-19 03:46:35

标签: java json jsonpath

问题:

我有一个服务,它接受一个JSON字符串作为输入。每次某些字段不总是存在时,JSON模式都不同。如何使用Jayway的JsonPath来查询这些字段的值?

我尝试过的事情:

我使用Option.DEFAULT_PATH_LEAF_TO_NULL作为Jayway'} readme page解释

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:路径中缺少属性$ [&#39; somepath&#39;]

当我给它一条不存在的道路时。有谁知道可能导致这种情况的原因?

1 个答案:

答案 0 :(得分:7)

我意识到我做错了什么。 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