Posts

Showing posts from September, 2013

A brief tutorial on using Guava's Optional with Jackson JSON library

One serious limitation of using Jackson to deserialize the custom defined bean classe is that you cannot differentiate between a value missing in the input JSON or it is present but having null value. Consider the exampel below: class MyBean { private String firstName; private String lastName; // Getters and setters here. } You cannot differentiate between the JSON inputs {"firstName": "John"} and {"firstName": "John", "lastName": null}. I.e. the lastName property being present in the input or not. Guava library has an excellent tool to express missing values versus null values: Optional . Jackson supports integration with Guava library. The integration library can be accessed from jackson-datatype-guava package. To clearly express the null versus absent values, we can rewrite the bean class above as follows: class MyBean { private Optional<String> firstName; private Optional<String> lastName; // Ge