Optional JsonPath using Jayway
<p><strong>Question:</strong></p>

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

<p><strong>What I've tried:</strong></p>

<p>I used the <code>Option.DEFAULT_PATH_LEAF_TO_NULL</code> as Jayway's <a href="https://github.com/jayway/JsonPath" rel="noreferrer">readme page</a> explained</p>

<pre><code>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&lt;String&gt; attributeValuesArray = JsonPath.using(config).parse(currentTx).read(attribute.jsonPath);

    for (String value : attributeValuesArray)
    {
        if (value != null)
        {
            attributeValues.add(value);
        }
    }
}
</code></pre>

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

<blockquote>
  <p>com.jayway.jsonpath.PathNotFoundException: Missing property in path $['somepath']</p>
</blockquote>

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