如何在使用 JSONPath 的数组中使用非空检查路径

How to use a path with nonNull check in an array using JSONPath

我有一个简单的json喜欢

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

在某些情况下,这个 books 数组可能像这样是空的

{
    "store": {
        "book": [ ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

我的解析代码如下

Configuration conf = Configuration.builder().jsonProvider(new JsonSmartJsonProvider())
                    .options(Option.SUPPRESS_EXCEPTIONS).build();
Object document = conf.jsonProvider().parse(objectInArray.toString());

String author = JsonPath.read(document, "$.store.book[0].author");

虽然 运行 这段代码我得到一个错误说

com.jayway.jsonpath.PathNotFoundException: Expected to find an object with property ['name'] in path $['store']['book'] but found 'null'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.


如何解决这个问题?我已经在使用抑制异常选项。这听起来很简单,但无法通过网络找到明确的解决方案。从数组中获取特定元素但不处理空数组的过滤条件示例。

我认为您的解析方法只是忽略了选项。像这样尝试:

String author = JsonPath.using(conf).parse(objectInArray.toString()).read("$.store.book[0].author");

我在原始文档中找到了这个方法: https://github.com/json-path/JsonPath#tweaking-configuration