本文介绍了使用Jayway的可选JsonPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

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

I have a service that takes in a JSON string as input. The JSON schema is different every time where some fields are not always present. How can I query the values of those fields using Jayway's JsonPath when they are present?

我尝试过的事情:

我使用Option.DEFAULT_PATH_LEAF_TO_NULL作为Jayway的自述页面解释

I used the Option.DEFAULT_PATH_LEAF_TO_NULL as Jayway's readme page explained

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,但是我的代码仍然抛出:

This should make JsonPath.read() return null if the path is not found, however my code still throws:

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

when I give it a inexistent path. Does anyone know what might be causing this?

推荐答案

我意识到自己做错了. DEFAULT_PATH_LEAF_TO_NULL选项仅照顾叶节点.例如:

I realized what I did wrong. The DEFAULT_PATH_LEAF_TO_NULL option only takes care of leaf nodes. For example:

Json示例

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

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

If $.foo.tmp is queried, JsonPath will return null as tmp is suppose to be a leaf node.

如果查询$.tmp.tmp2,JsonPath将抛出

If $.tmp.tmp2 is queried, JsonPath will throw a

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

In order to bypass this, one should use Option.SUPPRESS_EXCEPTIONS.

这篇关于使用Jayway的可选JsonPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 05:28