繁体   English   中英

使用Jayway的可选JsonPath

[英]Optional JsonPath using Jayway

题:

我有一个服务,它接受一个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']中缺少属性

当我给它一条不存在的道路时。 有谁知道这可能导致什么?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM