I have an object with one optional field and can not find proper annotation to model it. Any ideas what is the proper way to do it with Jackson?
In Jackson you cannot make the difference between optional and non-optional fields. Just declare any field in your POJO. If a field is not present in your JSON structure then Jackson will not call the setter. You may keep track of wether a setter has been called with a flag in the POJO.
You can mark a property as required with the @JsonProperty(required = true) annotation, and it will throw a JsonMappingException during deserialization if the property is missing or null.
That Optional is not serializable is also noted as a disadvantage of the new type here (especially in the comments) and here. To establish the facts: Optional does not implement Serializable. And it is final, which prevents users from creating a serializable subclass.
In Jackson you cannot make the difference between optional and non-optional fields. Just declare any field in your POJO. If a field is not present in your JSON structure then Jackson will not call the setter. You may keep track of wether a setter has been called with a flag in the POJO.
Coming late to the party...
Using Jackson 2.8.6 via Spring HttpMessageConverter 4.3.6, I had to change my setter parameter to the unwrapped type, like so:
class Foo { private Optional<Bar> bar; public void setBar(Bar bar) { // NOT Optional<Bar>, this gives me Optional.empty() this.bar = Optional.of(bar); } // getter doesn't need to be changed }
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