Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson use JsonSerialize.Inclusion.NON_NULL except for one class

Tags:

I normally use objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL) because I never want the null values of my classes serialized. Except now I have a specific field should be written out, even if it is null. Is there a quick annotation I can put on this one field that overrides the Inclusion.NON_NULL property for that one field? What's a good way to achieve this?

like image 332
newmanne Avatar asked Aug 28 '12 15:08

newmanne


People also ask

What is the use of @JsonInclude JsonInclude include Non_null?

In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.

What is JSON include non null?

Include. NON_NULL: Indicates that only properties with not null values will be included in JSON. Include. NON_EMPTY: Indicates that only properties that are not empty will be included in JSON. Non-empty can have different meaning for different objects such as List with size zero will be considered as empty.

What is @jsonserialize?

An object that converts between JSON and the equivalent Foundation objects. iOS 5.0+ iPadOS 5.0+ macOS 10.7+ Mac Catalyst 13.1+ tvOS 9.0+ watchOS 2.0+

What is @JsonInclude?

@JsonInclude It says that if the value of a property (or all properties) in question is equal to a certain value ( null , empty - whatever that means, or a default value) this property is not serialized. Without this annotation, the property value is always serialized.


2 Answers

With Jackson 1.x you can use @JsonSerialize(include = Inclusion.ALWAYS) and with Jackson 2.x you can use @JsonInclude(Include.ALWAYS). These annotations will override the default config from your ObjectMapper.

like image 97
Pascal Gélinas Avatar answered Oct 06 '22 15:10

Pascal Gélinas


@user1433372, JsonInclude is an annotation only for Jackson 2.x.

in Jackson 1.9

@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY) 

is the same in Jackson 2.x as

@JsonInclude(JsonInclude.Include.NON_EMPTY) 
like image 34
Marcus Avatar answered Oct 06 '22 17:10

Marcus