Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional JsonPath using Jayway

Question:

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?

What I've tried:

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

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

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

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

like image 209
SegFault Avatar asked Jul 19 '16 03:07

SegFault


People also ask

What is Jayway JsonPath?

Jayway JsonPath. A Java DSL for reading JSON documents. Jayway JsonPath is a Java port of Stefan Goessner JsonPath implementation.

Does Jackson support JsonPath?

The Jayway JsonPath library has support for reading values using a JSON path. If you would like to specifically use GSON or Jackson to do the deserialization (the default is to use json-smart), you can also configure this: Configuration.

What is difference between JSON & JsonPath?

JSONPath creates a uniform standard and syntax to define different parts of a JSON document. JSONPath defines expressions to traverse through a JSON document to reach to a subset of the JSON. This topic is best understood by seeing it in action. We have created a web page which can help you evaluate a JSONPath.


1 Answers

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

Sample Json

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

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

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

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

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

like image 154
SegFault Avatar answered Oct 15 '22 17:10

SegFault