Optional JsonPath using Jayway

PhotometricStereo picture PhotometricStereo · Jul 19, 2016 · Viewed 10.8k times · Source

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?

Answer

PhotometricStereo picture PhotometricStereo · Jul 19, 2016

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.