0 votes
1 view
in Java by (3.1k points)

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; 

}

1 Answer

0 votes
by (21.7k points)

To overcome serializing properties with null values using Jackson >2.0, you can configure the ObjectMapper instantly, 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 property would be shown if the value is not null.

To handle the null Map keys, some custom serialization is required, as best I understand.

A simple method to serialize null keys as empty strings (including complete examples of previously mentioned configurations):

import java.io.IOException;

import java.util.HashMap;

import java.util.Map;

import com.fasterxml.jackson.annotation.JsonInclude.Include;

import com.fasterxml.jackson.core.JsonGenerator;

import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.databind.JsonSerializer;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.fasterxml.jackson.databind.SerializationFeature;

import com.fasterxml.jackson.databind.SerializerProvider;

public class JacksonFoo

{

  public static void main(String[] args) throws Exception

  {

    Map<String, Foo> foos = new HashMap<String, Foo>();

    foos.put("foo1", new Foo("foo1"));

    foos.put("foo2", new Foo(null));

    foos.put("foo3", null);

    foos.put(null, new Foo("foo4"));

    // System.out.println(new ObjectMapper().writeValueAsString(foos));

    // Exception: A null key for a Map isn't allowed in JSON (use a converting NullKeySerializer?)

    ObjectMapper mapper = new ObjectMapper();

mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);

mapper.setSerializationInclusion(Include.NON_NULL);

mapper.getSerializerProvider().setNullKeySerializer(new MyNullKeySerializer());   System.out.println(mapper.writeValueAsString(foos));

    // output: 

    // {"":{"bar":"foo4"},"foo2":{},"foo1":{"bar":"foo1"}}

  }

class MyNullKeySerializer extends JsonSerializer<Object>

{

  @Override

  public void serialize(Object nullKey, JsonGenerator jsonGenerator, SerializerProvider unused) 

      throws IOException, JsonProcessingException

  {   jsonGenerator.writeFieldName("");

  }

}

class Foo

{

  public String bar;

  Foo(String bar)

  {

    this.bar = bar;

  }

}

...