1

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.

Community
  • 1
  • 1
Richard
  • 5,840
  • 36
  • 123
  • 208
  • Possible duplicate of [How to tell Jackson to ignore a field during serialization if its value is null?](http://stackoverflow.com/questions/11757487/how-to-tell-jackson-to-ignore-a-field-during-serialization-if-its-value-is-null) – ΦXocę 웃 Пepeúpa ツ Mar 14 '16 at 20:27
  • This isn't a duplicate because I'm not serializing into an object. I'm just extracting 1 value – Richard Mar 14 '16 at 20:31

1 Answers1

1

You can use code like so:

Optional<Boolean> b = Optional.ofNullable(json.get("b"))
                              .map(node -> node.asBoolean());

A couple of points worth noting:

  • You don't need to use filter. ofNullable is going to return an empty nullable. According to Jackson documentation, null is returned if node value is not present.
  • Closely related to your question about s in referenced question, map is a function that is run only when the Optional is present (e.g. JSON has b value). It takes a lambda expression which is an equivalent of using an anonymous class. node is a parameter for the Function interface that has only one method (apply). You can take a look at the examples here.
Alex Panov
  • 758
  • 10
  • 11