Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson serialization: ignore empty values (or null)

Tags:

java

json

jackson

People also ask

How do you tell Jackson to ignore a field during serialization if its null?

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.

Does Jackson serialize null fields?

With its default settings, Jackson serializes null-valued public fields. In other words, resulting JSON will include null fields. Here, the name field which is null is in the resulting JSON string.

How can I skip optional empty field in Jackson serialization?

To exclude Optional. empty() fields, as the OP originally asked, one MUST add the depencandy and MUST set NON_ABSENT. NON_NULL is not enough.

How do I ignore null fields in Jackson?

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.


You have the annotation in the wrong place - it needs to be on the class, not the field. i.e:

@JsonInclude(Include.NON_NULL) //or Include.NON_EMPTY, if that fits your use case 
public static class Request {
  // ...
}

As noted in comments, in versions below 2.x the syntax for this annotation is:

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) // or JsonSerialize.Inclusion.NON_EMPTY

The other option is to configure the ObjectMapper directly, simply by calling mapper.setSerializationInclusion(Include.NON_NULL);

(for the record, I think the popularity of this answer is an indication that this annotation should be applicable on a field-by-field basis, @fasterxml)


You can also set the global option:

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

Also you can try to use

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

if you are dealing with jackson with version below 2+ (1.9.5) i tested it, you can easily use this annotation above the class. Not for specified for the attributes, just for class decleration.


You need to add import com.fasterxml.jackson.annotation.JsonInclude;

Add

@JsonInclude(JsonInclude.Include.NON_NULL)

on top of POJO

If you have nested POJO then

@JsonInclude(JsonInclude.Include.NON_NULL)

need to add on every values.

NOTE: JAXRS (Jersey) automatically handle this scenario 2.6 and above.