Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define optional json field using Jackson

Tags:

java

json

jackson

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?

like image 235
mkorszun Avatar asked Oct 23 '13 19:10

mkorszun


People also ask

How do you make a field optional in 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.

How do I make a JSON property mandatory?

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.

Can optional be serialized?

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.


2 Answers

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.

like image 103
mwhs Avatar answered Sep 23 '22 08:09

mwhs


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 } 
like image 32
pyb Avatar answered Sep 24 '22 08:09

pyb