61

I have a a Map<String,Foo> foosMap that I want to serialize through Jackson . Now I want following two settings on the serialization process:

  1. The Map can have have plenty of null values and null keys and I don't want nulls to be serialized.
  2. For all those Foos that are getting serialized, I do not want to serialize null objects referenced inside Foo.

What is the best way to achieve this ? I am using jackson-core1.9 and jackson-mapper1.9 jars in my project.

4

4 Answers 4

128

If it's reasonable to alter the original Map data structure to be serialized to better represent the actual value wanted to be serialized, that's probably a decent approach, which would possibly reduce the amount of Jackson configuration necessary. For example, just remove the null key entries, if possible, before calling Jackson. That said...


To suppress serializing Map entries with null values:

Before Jackson 2.9

you can still make use of WRITE_NULL_MAP_VALUES, but note that it's moved to SerializationFeature:

mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);

Since Jackson 2.9

The WRITE_NULL_MAP_VALUES is deprecated, you can use the below equivalent:

mapper.setDefaultPropertyInclusion(
   JsonInclude.Value.construct(Include.ALWAYS, Include.NON_NULL))

To suppress serializing properties with null values, 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
{
  public String bar;

  Foo(String bar)
  {
    this.bar = bar;
  }
}

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

A simple approach to serialize null keys as empty strings (including complete examples of the two 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: Null key for a Map not 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;
  }
}

To suppress serializing Map entries with null keys, further custom serialization processing would be necessary.

5
  • 2
    Just a caveat these directions are Jackson 2.0 specific (com.fasterxml vs org.codehaus).
    – Adam Gent
    Apr 3, 2013 at 20:15
  • @ProgrammerBruce - Is it possible to prevent null-field serialization for a specific class in the object mapper? eg: Use the same object mapper to serialize class A and B, but only null-fields in class B are ignored. Dec 9, 2016 at 6:55
  • @ProgrammerBurce - as the jackson has upgraded to 2.9, the WRITE_NULL_MAP_VALUES is deprecated. Do you know is there an alternative way to do the same?
    – Aiden Zhao
    Jan 12, 2018 at 19:32
  • I find the equivalent of WRITE_NULL_MAP_VALUES since 2.9: mapper.setDefaultPropertyInclusion(JsonInclude.Value.construct(Include.ALWAYS, Include.NON_NULL))
    – Aiden Zhao
    Jan 12, 2018 at 23:32
  • @AidenZhao - I have jackson 2.9.2. My IDE, Intellij IDEA does not show any method called "setDefaultPropertyInclusion" for com.fasterxml.jackson.databind.ObjectMapper. Am I missing something ?
    – MasterJoe
    Jul 3, 2018 at 16:51
19

For Jackson versions < 2.0 use this annotation on the class being serialized:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
3
  • 5
    FYI, this is deprecated, the accepted answer above has the latest annotation: @JsonInclude(Include.NON_NULL)
    – Amber
    Nov 30, 2015 at 17:47
  • Note that the JsonInclude annotation is not available if you are using Jackson 1.9.x in which case you will have to use the JsonSerialize annotation. Mar 16, 2016 at 17:24
  • I confirm with Jackson 1.9.x the @JsonInclude(Include.NON_NULL) doesn't work. I'm importing this package: org.codehaus.jackson.map
    – Emanuele
    Jan 5, 2018 at 20:52
3

Answer seems to be a little old, What I did was to use this mapper to convert a MAP

      ObjectMapper mapper = new ObjectMapper().configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);

a simple Map:

          Map<String, Object> user = new HashMap<String,Object>();
            user.put( "id",  teklif.getAccount().getId() );
            user.put( "fname", teklif.getAccount().getFname());
            user.put( "lname", teklif.getAccount().getLname());
            user.put( "email", teklif.getAccount().getEmail());
            user.put( "test", null);

Use it like this for example:

      String json = mapper.writeValueAsString(user);
1
  • 2
    Please add the output of the json. Jan 29, 2020 at 5:58
-1

my solution, hope help
custom ObjectMapper and config to spring xml(register message conveters)

public class PyResponseConfigObjectMapper extends ObjectMapper {
public PyResponseConfigObjectMapper() {
    disable(SerializationFeature.WRITE_NULL_MAP_VALUES); //map no_null
    setSerializationInclusion(JsonInclude.Include.NON_NULL); // bean no_null
}

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.