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?
Jayway JsonPath. A Java DSL for reading JSON documents. Jayway JsonPath is a Java port of Stefan Goessner JsonPath implementation.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With