6

I'm using Jackson 2.4 to serialize objects to JSON.
When I serialize a list of objects, having some elements are null, the result JSON string contains some "null" strings.

How do I prevent "null" elements from being serialized? Is there any configuration for ObjectMapper? I have already set "setSerializationInclusion(Include.NON_NULL)"!

Here is my code :

List<String> strings = new ArrayList<>();
strings.add("string 1");
strings.add("string 2");
strings.add(null);
strings.add(null);

After serializing I got this :

[string 1, string 2, null, null]

How do I get the JSON string without "null"?

[string 1, string 2]
toandv
  • 982
  • 13
  • 25
  • 1
    Why are you adding the nulls if you don't want them? – Hot Licks Dec 03 '14 at 03:07
  • It's just an example, in some cases, a collection may contain null elements, I just want to know if Jackson is able to ignore null members in a collection, or I have to make the collection null-free. – toandv Dec 03 '14 at 03:49

4 Answers4

5

Using @JsonInclude annotation.

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

}

Edit

Also you can create your own serializer.
For example :

public static void main(String[] args) throws JsonProcessingException {

        List<String> strings = new ArrayList<>();
        strings.add("string 1");
        strings.add("string 2");
        strings.add(null);
        strings.add(null);

        ObjectMapper mapper=new ObjectMapper();
        mapper.getSerializerProvider().setNullValueSerializer(new NullSerializer());
        System.out.println(mapper.writeValueAsString(strings));
    }

NullSerializer.java

class NullSerializer extends JsonSerializer<Object>
{
  @Override
  public void serialize(Object obj, JsonGenerator jsonGen, SerializerProvider unused) 
      throws IOException, JsonProcessingException
  {
    jsonGen.writeFieldName("");
  }
}

Will print

["string 1","string 2","",""]

then you can remove jsonGen.writeFieldName(""); to print

["string 1","string 2"]
Ken de Guzman
  • 2,790
  • 1
  • 19
  • 33
  • NullSerializer solves problem with null values in arrays, Include.NON_EMPTY solves skipping of keys with empty collections and keys with null values. – Michal Bernhard Aug 06 '15 at 11:19
2

Suggestion of implementing a custom NullSerializer is a great idea, in my case I don't want all null values to be ignored (eg, outside collections) so with just a small tweak you can have both things working.

class NullSerializer extends JsonSerializer<Object>{
    @Override
    public void serialize(Object obj, JsonGenerator jsonGen, SerializerProvider unused) 
  throws IOException, JsonProcessingException {
        //any null outside of a collection will be serialized (as long as SerilizationInclusion allows nulls)
        if (!jsonGen.getOutputContext().inArray()) {
            jsonGen.writeNull();
        }
    }
}

Using that custom NullSerializer, serializing following class:

class MyTest {
    public List<String> list = Arrays.asList("hello", null, "world", null);
    public Object goodNull = null;
}

Produces the JSON:

{ "list":["hello","world"], "goodNull":null}
1

try using below

@JsonInclude(Include.NON_NULL)

also refer this for more detailed explanation.

Community
  • 1
  • 1
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
0

You can prevent it by :

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) private String checkNullThenSerialize;

put this on Member declaration.

or you can put class level also like :

@JsonInclude(Include.NON_NULL)
class CheckNullThenSerialize{
  private String fieldData;
  private String fieldNull;
}

You can also try Include.NON_EMPTY with @JsonInclude alter to Include.NON_NULL.

For ObjectMapper (Any null field in any class serialized through this mapper is going to be ignored):

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);

Look Here's full details on this topic.

user3145373 ツ
  • 7,858
  • 6
  • 43
  • 62