Search code examples
javajsonjsonpathjson-path-expression

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


I have a simple json like

{
    "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
}

In some cases, this books array may be empty like this

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

My code to parse this is like below

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");

While running this code I get an error saying

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'.


How do I solve this issue? I am already using suppress exceptions options. It sounds pretty simple but not able to find a clear solution over web. Examples side a filter criteria for getting specific element from array but not for handling empty array.


Solution

  • I think that your method of parsing just ignores the options. Try it like this:

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

    I found this method on the original documentation: https://github.com/json-path/JsonPath#tweaking-configuration