Reputation: 1487
I have a Java Object that I want to serialise to JSON. However, before I do that, I set some properties on fields for that object. Now I want to serialise this object to JSON. How can I serialise only the fields that were explicitly assigned a value and basically exclude all other fields?
For me, adding these annotations above the object class do not work: @JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
and @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
. The reason is that I have fields with primitive data types. By adding one of the above two annotations, I am not preventing primitive data type fields from being serialised. For example, I have several boolean fields that will be serialised with their default value false
. However, I do not want these fields to appear in the JSON result, as I have not explicitly set their values before the serialisation process. Any thoughts?
For further information: I am using the Jackson ObjectMapper.
Upvotes: 0
Views: 1066
Reputation: 280148
Starting with Jackson 2.6, use @JsonInclude
with Include.NON_DEFAULT
.
Value that indicates that only properties that have values that differ from default settings (meaning values they have when Bean is constructed with its no-arguments constructor) are to be included.
Jackson will create an throwaway instance of your class so it can verify which property values are different from the defaults, and only serialize those.
Upvotes: 2