使用 Jayway 的可选 JsonPath

Optional JsonPath using Jayway

问题:

我有一项服务接受 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() return null,但是我的代码仍然抛出:

com.jayway.jsonpath.PathNotFoundException: Missing property in path $['somepath']

当我给它一个不存在的路径时。有谁知道这可能是什么原因造成的?

我意识到我做错了什么。 DEFAULT_PATH_LEAF_TO_NULL 选项只处理叶节点。例如:

样本Json

{
    "foo":{
        "bar":"value"
    }
}

如果 $.foo.tmp 被查询,JsonPath 将 return null 因为 tmp 被假定为叶节点。

如果查询$.tmp.tmp2,JsonPath会抛出一个

com.jayway.jsonpath.PathNotFoundException as tmp isn't a leaf and is not present.

为了绕过这个,应该使用Option.SUPPRESS_EXCEPTIONS