850

How can Jackson be configured to ignore a field value during serialization if that field's value is null.

For example:

public class SomeClass {
   // what jackson annotation causes jackson to skip over this value if it is null but will 
   // serialize it otherwise 
   private String someValue; 
}
0m3r
  • 12,286
  • 15
  • 35
  • 71
ams
  • 60,316
  • 68
  • 200
  • 288

22 Answers22

1313

To suppress serializing properties with null values using Jackson >2.0, you can configure the ObjectMapper directly, or make use of the @JsonInclude annotation:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

Alternatively, you could use @JsonInclude in a getter so that the attribute would be shown if the value is not null.

A more complete example is available in my answer to How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson.

Peter Wippermann
  • 4,125
  • 5
  • 35
  • 48
Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
  • 90
    for my project, this worked: `@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)`; somehow your annotation wasn't available. – Emmanuel Touzery Mar 11 '13 at 13:53
  • 14
    The API changed a bit with the 2.0 release. – Programmer Bruce Mar 11 '13 at 16:55
  • @JsonInclude(Include.NON_NULL) works like a champ when I create a new object with some properties (but some null) and then serialize it to JSON. However, oddly, when I grab an object using a DAO of sorts then serialize that, it doesn't appear to take effect and I get the null properties again. It may not be playing nice with Hibernate or DropWizard, but does any of this ring a bell? Are there times where @JsonInclude would be ignored? – Depressio Apr 18 '13 at 06:45
  • 12
    @ProgrammerBruce -1 change your answer accordingly since you're aware of the change. – Martin Asenov Apr 30 '13 at 13:08
  • 23
    Yeah, I just confirmed that the `@JsonInclude` notation doesn't work, but this works like a charm: `@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)` (I'm using Jackson 1.9.12 with Spring 3.2.2.) – gstroup May 02 '13 at 23:04
  • Maybe I am being daft here, but when I add that to my class I get: error: class, interface, or enum expected – Gerrie Jul 17 '13 at 10:35
  • `JsonInclude(Include.NON_NULL)` works fine with Jersey – slf Jun 05 '14 at 16:17
  • @Depressio: Facing that exact issue - did you find out how to fix it? – jeffreyveon Mar 05 '15 at 10:04
  • 26
    @MartinAsenov - the answer shows the most recent API; it was changed from the `@JsonSerialize` syntax to `@JsonInclude`. The older syntax is deprecated. – Logan Pickup Mar 10 '15 at 21:23
  • @jeffreyveon it was a Jackson version mismatch between my annotations and what other tools were using. One tool was using the Jackson 1.x ObjectMapper, another was using the Jackson 2.x one. The annotation sets are mutually exclusive due to re-packaging. – Depressio Mar 11 '15 at 18:06
  • 5
    If serializing an object that may have an empty array, NON_EMPTY will do the trick: `@JsonInclude(JsonInclude.Include.NON_EMPTY)` – Philippe Jan 11 '16 at 19:31
  • can i tell jackson also to ignore null objects? Like {["bla": {"name": "bla1"},null]} – Fabian Feb 01 '16 at 14:09
  • 2
    Some software is still stuck in 2016 with 1.9 - without bold notice this answer is very inconvenient time waster. – Boris Treukhov Jul 29 '16 at 22:33
  • If Eclipse is not finding `Include` in the classpath, try `JsonInclude.Include` instead. – Steve Apr 11 '17 at 21:41
  • Put @JsonInclude(JsonInclude.Include.NON_NULL) on a field not the class – Pashec Nov 16 '17 at 14:49
  • The class level annotation : @JsonInclude(Include.NON_NULL) worked like a charm – Vijay Kumar Nov 30 '17 at 20:06
  • I am using `@JsonInclude(Include.NON_NULL) ` for one of my classes. But now I need to send over one of the properties even with a null value. How do I do this? – Rajeev Ranjan Dec 07 '17 at 09:26
  • doesn't work for ObjectNode ```mapper.writeValueAsString(mapper.createObjectNode().putNull("nullval")))``` is there a way to fix this? – Pavel K. Feb 20 '18 at 10:02
  • Can I use for this `FAIL_ON_EMPTY_BEANS` also? – Coding world Jun 25 '19 at 05:30
  • JsonSerialize.Inclusion.* is deprecated. – Akito Nov 25 '21 at 13:26
  • import com.fasterxml.jackson.annotation.JsonInclude; //Maybe that will help someone as I had to chase down the right import since I had multiple jackson ObjectMapper libraries in my class path. – thebiggestlebowski Dec 20 '21 at 14:50
187

Just to expand on the other answers - if you need to control the omission of null values on a per-field basis, annotate the field in question (or alternatively annotate the field's 'getter').

example - here only fieldOne will be omitted from the JSON if it is null. fieldTwo will always be included in the JSON regardless of if it is null.

public class Foo {

    @JsonInclude(JsonInclude.Include.NON_NULL) 
    private String fieldOne;

    private String fieldTwo;
}

To omit all null values in the class as a default, annotate the class. Per-field/getter annotations can still be used to override this default if necessary.

example - here fieldOne and fieldTwo will be omitted from the JSON if they are null, respectively, because this is the default set by the class annotation. fieldThree however will override the default and will always be included, because of the annotation on the field.

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

    private String fieldOne;

    private String fieldTwo;
    
    @JsonInclude(JsonInclude.Include.ALWAYS)
    private String fieldThree;
}

UPDATE

The above is for Jackson 2. For earlier versions of Jackson you need to use:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) 

instead of

@JsonInclude(JsonInclude.Include.NON_NULL)

If this update is useful, please upvote ZiglioUK's answer below, it pointed out the newer Jackson 2 annotation long before I updated my answer to use it!

davnicwil
  • 28,487
  • 16
  • 107
  • 123
  • shouldn't the annotation on the field be ALWAYS to override ? – Abhinav Vishak Jan 17 '18 at 22:17
  • @AbhinavVishak you are right - thanks! It was a copy-paste typo when I updated the answer to use Jackson 2. Edited. – davnicwil Jan 18 '18 at 08:04
  • `@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) ` is deprecated – Yar Feb 13 '18 at 18:20
  • 1
    @Yar yes, that's deprecated in Jackson 2.x. I've stated that you need to use that only in earlier versions of Jackson where not only it is *not* deprecated, it's the only option. – davnicwil Feb 13 '18 at 21:11
140

With Jackson > 1.9.11 and < 2.x use @JsonSerialize annotation to do that:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

WTK
  • 16,583
  • 6
  • 35
  • 45
67

In Jackson 2.x, use:

@JsonInclude(JsonInclude.Include.NON_NULL)
Matthew Read
  • 1,365
  • 1
  • 30
  • 50
ZiglioUK
  • 2,573
  • 4
  • 27
  • 32
  • is this to be placed on the field. – ams Jan 20 '14 at 17:35
  • 1
    @ams , this annotation should wrapper a class – Edgard Leal Apr 04 '17 at 17:12
  • Could you also include the fully qualified name? Jackson has multiple annotations with the same name and a different package, so that is ambiguous. – Vince Sep 11 '17 at 09:49
  • are you saying there are multiple @JsonInclude annotations in Jackson? I had no idea. What should the fully qualified name be then? feel free to edit the answer – ZiglioUK Sep 12 '17 at 08:44
  • Confusion with names is most likely due to Jackson 1.x and 2.x using different Java packages for everything, to avoid class loader conflicts (wrt incompatible class versions). Since this answer is for 2.x, package for annotations would be `com.fasterxml.jackson.annotation` -- Jackson 1.x had `org.codehaus.jackson.annoation` – StaxMan Sep 20 '17 at 05:26
47

You can use the following mapper configuration:

mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);

Since 2.5 you can user:

mapper.setSerializationInclusion(Include.NON_NULL);
Arturo Volpe
  • 3,442
  • 3
  • 25
  • 40
Eren Yilmaz
  • 1,082
  • 12
  • 21
  • 3
    Since this is deprecated in 1.9, use mapper.getSerializationConfig().withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); – Asa Apr 30 '14 at 02:38
  • 7
    ..or directly: mapper.setSerializationInclusion(NON_NULL); – Asa Apr 30 '14 at 05:55
  • @ruslan: Probably because the documentation of `getSerializationConfig() `says: `Note that since instances are immutable, you can NOT change settings by accessing an instance and calling methods: this will simply create new instance of config object.` – Zero3 Sep 12 '15 at 14:05
  • For 2.5.4 use `mapper.setSerializationInclusion(Include.NON_NULL);` – Arturo Volpe Sep 26 '16 at 21:33
45

You can set application.properties:

spring.jackson.default-property-inclusion=non_null

or application.yaml:

spring:
  jackson:
    default-property-inclusion: non_null

http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

pXel
  • 599
  • 5
  • 18
Yury
  • 551
  • 4
  • 8
13

in my case

@JsonInclude(Include.NON_EMPTY)

made it work.

alfthan
  • 463
  • 4
  • 13
  • 3
    NON_EMPTY is subtly different from NON_NULL - it will ignore null values, that's true, but will *also* ignore values considered empty, which may not be the desired behaviour. See the Jackson [javadocs](http://fasterxml.github.io/jackson-annotations/javadoc/2.7/) for more info – davnicwil Jun 23 '16 at 14:50
  • i like this answer because returning Optional from things that are really optional is a good idea, and with just NON_NULL you would get something like `{ }` for null, which pointlessly transfers a Java idiom to the consumer. same with AtomicReference--the consumer doesn't care how the developer chose to enforce thread safety on the internal representation of the response. – Lucas Ross Dec 08 '17 at 05:46
11
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonInclude(JsonInclude.Include.NON_EMPTY)

should work.

Include.NON_EMPTY indicates that property is serialized if its value is not null and not empty. Include.NON_NULL indicates that property is serialized if its value is not null.

Neha Gangwar
  • 670
  • 9
  • 14
6

This Will work in Spring boot 2.0.3+ and Jackson 2.0+

import com.fasterxml.jackson.annotation.JsonInclude;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiDTO
{
    // your class variable and 
    // methods
}
Deva
  • 1,851
  • 21
  • 22
  • 1
    That same `@JsonInclude(JsonInclude.Include.NON_NULL)` worked for me on **Spring boot 2.1.2** and **Jackson annotations 2.9.0** – manasouza Feb 09 '19 at 12:09
  • @manasouza Yes, they have maintained consistency to all updates. – Deva Feb 11 '19 at 06:08
5

If you want to add this rule to all models in Jackson 2.6+ use:

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
Ilia Kurtov
  • 999
  • 1
  • 12
  • 18
5

If in Spring Boot, you can customize the jackson ObjectMapper directly through property files.

Example application.yml:

spring:
  jackson:
    default-property-inclusion: non_null # only include props if non-null

Possible values are:

always|non_null|non_absent|non_default|non_empty

More: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
4

For Jackson 2.5 use :

@JsonInclude(content=Include.NON_NULL)
Bilal BBB
  • 1,154
  • 13
  • 20
3

If you're trying to serialize a list of object and one of them is null you'll end up including the null item in the JSON even with

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

will result in:

[{myObject},null]

to get this:

[{myObject}]

one can do something like:

mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
        @Override
        public void serialize(Object obj, JsonGenerator jsonGen, SerializerProvider unused)
                throws IOException
        {
            //IGNORES NULL VALUES!
        }
    });

TIP: If you're using DropWizard you can retrieve the ObjectMapper being used by Jersey using environment.getObjectMapper()

Ihor Patsian
  • 1,288
  • 2
  • 15
  • 25
user3474985
  • 983
  • 8
  • 20
3

Global configuration if you use Spring

@Configuration
public class JsonConfigurations {

    @Bean
    public Jackson2ObjectMapperBuilder objectMapperBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);
        builder.failOnUnknownProperties(false);
        return builder;
    }

}
Xelian
  • 16,680
  • 25
  • 99
  • 152
  • Setting the serializationInclusion does not add one on another. `public Jackson2ObjectMapperBuilder serializationInclusion(JsonInclude.Include serializationInclusion) { this.serializationInclusion = serializationInclusion; return this; }` ; One should use the greater radius of inclusion enumeration. e.g NON_ABSENT includes NON_NULL and NON_EMPTY includes both. Thus it only should be `builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);` [JacksonInclude doc](https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonInclude.Include.html) – Olgun Kaya Feb 18 '19 at 07:58
2

This has been troubling me for quite some time and I finally found the issue. The issue was due to a wrong import. Earlier I had been using

com.fasterxml.jackson.databind.annotation.JsonSerialize

Which had been deprecated. Just replace the import by

import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

and use it as

@JsonSerialize(include=Inclusion.NON_NULL)
prateek_cs_2012
  • 55
  • 1
  • 10
1

We have lot of answers to this question. This answer may be helpful in some scenarios If you want to ignore the null values you can use the NOT_NULL in class level. as below

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

Some times you may need to ignore the empty values such as you may have initialized the arrayList but there is no elements in that list.In that time using NOT_EMPTY annotation to ignore those empty value fields

@JsonInclude(Include.NON_EMPTY)
class Foo
{
  String bar;
}
1

Case one

@JsonInclude(JsonInclude.Include.NON_NULL)
private String someString;

Case two

@JsonInclude(JsonInclude.Include.NON_EMPTY)
private String someString;

If someString is null, it will be ignored on both of cases. If someString is "" it just only be ignored on case two.

The same for List = null or List.size() = 0

Nguyen Minh Hien
  • 455
  • 7
  • 10
1

Try this -

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class XYZ {
    
    protected String field1;
    
    protected String field2;
 }

And for non-null values (On getters/class level) -

@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)
0

Jackson 2.x+ use

mapper.getSerializationConfig().withSerializationInclusion(JsonInclude.Include.NON_NULL);
mekdev
  • 468
  • 6
  • 14
  • `.withSerializationInclusion(JsonInclude.Include.NON_NULL)` instead right ? – herau Oct 27 '14 at 14:21
  • Thanks for pointing that out, I'll hold off from upgrading :-( – ZiglioUK Mar 05 '15 at 23:01
  • @ruslan: Probably because the documentation of `getSerializationConfig()` says: `Note that since instances are immutable, you can NOT change settings by accessing an instance and calling methods: this will simply create new instance of config object.` – Zero3 Sep 12 '15 at 14:04
0

Also, you have to change your approach when using Map myVariable as described in the documentation to eleminate nulls:

From documentation:
com.fasterxml.jackson.annotation.JsonInclude

@JacksonAnnotation
@Target(value={ANNOTATION_TYPE, FIELD, METHOD, PARAMETER, TYPE})
@Retention(value=RUNTIME)
Annotation used to indicate when value of the annotated property (when used for a field, method or constructor parameter), or all properties of the annotated class, is to be serialized. Without annotation property values are always included, but by using this annotation one can specify simple exclusion rules to reduce amount of properties to write out.

*Note that the main inclusion criteria (one annotated with value) is checked on Java object level, for the annotated type, and NOT on JSON output -- so even with Include.NON_NULL it is possible that JSON null values are output, if object reference in question is not `null`. An example is java.util.concurrent.atomic.AtomicReference instance constructed to reference null value: such a value would be serialized as JSON null, and not filtered out.

To base inclusion on value of contained value(s), you will typically also need to specify content() annotation; for example, specifying only value as Include.NON_EMPTY for a {link java.util.Map} would exclude Maps with no values, but would include Maps with `null` values. To exclude Map with only `null` value, you would use both annotations like so:
public class Bean {
   @JsonInclude(value=Include.NON_EMPTY, content=Include.NON_NULL)
   public Map<String,String> entries;
}

Similarly you could Maps that only contain "empty" elements, or "non-default" values (see Include.NON_EMPTY and Include.NON_DEFAULT for more details).
In addition to `Map`s, `content` concept is also supported for referential types (like java.util.concurrent.atomic.AtomicReference). Note that `content` is NOT currently (as of Jackson 2.9) supported for arrays or java.util.Collections, but supported may be added in future versions.
Since:
2.0
atom88
  • 1,449
  • 3
  • 22
  • 32
0

In Jackson 2.0 or greater, @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) the include property was deprecated, we need replace with:

@JsonInclude(Include.NON_NULL)
public class MyClass
peterzinho16
  • 919
  • 1
  • 15
  • 18
0

@JsonInclude(Include.NON_EMPTY) OR @JsonInclude(Include.NON_NULL)