I am using the JsonNode objects from the Jackson library to hold json responses. I could potentially have a json like so:
{
"a": "test",
"b": true
}
However, at times the b
field could be missing. So it could come back like this:
{
"a": "test"
}
In that case I want to return Optional.isEmpty()
when I'm trying to retrieve its value. Essentially this is the java code for that:
if(json.path("b").isMissingNode()) {
return Optional.empty();
} else {
return Optional.of(json.get("b").asBoolean());
}
However, I want to condense this into 1 line using .filter
and .ofNullable
but I'm not exactly sure how to do this. I found this post that shows an example of how to use the filter but I understand what the s
is....
Basically I want to find the field labeled b
, if it's not there then return empty. If it is there then return the boolean value of it's field.
Edit: This is not a duplicate because I am not serializing the entire json into an object. I don't have any need for the JsonIgnore annotations. I only want to extract 1 value. Which is like above.