Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Spring Boot 1.2.3, how to set ignore null value in JSON serialization?

In the Spring Boot 1.2.3, we can customize the Jackson ObjectMapper via properties file. But I didn't find a attribute can set Jackson ignore null value when serialization the Object to JSON string.

spring.jackson.deserialization.*= # see Jackson's DeserializationFeature spring.jackson.generator.*= # see Jackson's JsonGenerator.Feature spring.jackson.mapper.*= # see Jackson's MapperFeature spring.jackson.parser.*= # see Jackson's JsonParser.Feature spring.jackson.serialization.*= 

I want to archive the same code like

ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(Include.NON_NULL); 
like image 263
crisli Avatar asked May 05 '15 00:05

crisli


People also ask

How do I ignore NULL values in JSON spring boot?

You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.

How do I ignore NULL values in post request body in spring boot?

Just use this @JsonSerialize(include = Inclusion. NON_NULL) instead of @JsonInclude(Include. NON_NULL) and it works..!!

How do you tell Jackson to ignore a field during Deserialization if its value is null?

Jackson default include null fields 1.2 By default, Jackson will include the null fields. To ignore the null fields, put @JsonInclude on class level or field level.

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.


2 Answers

Add the following line to your application.properties file.

spring.jackson.default-property-inclusion=non_null

For versions of Jackson prior to 2.7:

spring.jackson.serialization-inclusion=non_null

like image 86
cjungel Avatar answered Oct 13 '22 21:10

cjungel


This was a good solution before deprecation: @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

But now you should use:

@JsonInclude(JsonInclude.Include.NON_NULL) public class ClassName { ...

You can take a look here: https://fasterxml.github.io/jackson-annotations/javadoc/2.7/com/fasterxml/jackson/annotation/JsonInclude.Include.html

like image 31
Itay Avatar answered Oct 13 '22 19:10

Itay