Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson - serializing a list containing null elements

Tags:

java

jackson

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]
like image 569
toandv Avatar asked Dec 02 '14 10:12

toandv


Video Answer


1 Answers

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"]
like image 118
Ken de Guzman Avatar answered Sep 20 '22 08:09

Ken de Guzman