Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you override the null serializer in Jackson 2.0?

Tags:

java

json

jackson

I'm using Jackson for JSON serialization, and I would like to override the null serializer -- specifically, so that null values are serialized as empty strings in JSON rather than the string "null".

All of the documentation and examples I've found on how to set null serializers refers to Jackson 1.x -- for example, the code at the bottom of http://wiki.fasterxml.com/JacksonHowToCustomSerializers no longer compiles with Jackson 2.0 because StdSerializerProvider no longer exists in the library. That web page describes Jackson 2.0's module interface, but the module interface has no obvious way to override the null serializer.

Can anyone provide a pointer on how to override the null serializer in Jackson 2.0?

like image 588
uscjeremy Avatar asked Aug 07 '13 10:08

uscjeremy


1 Answers

Override the JsonSerializer serialize method as below.

public class NullSerializer extends JsonSerializer<Object> {
  public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    // any JSON value you want...  
    jgen.writeString("");
  }
}

then you can set NullSerializer as default for custom object mapper:

public class CustomJacksonObjectMapper extends ObjectMapper {

public CustomJacksonObjectMapper() {
    super();
    DefaultSerializerProvider.Impl sp = new DefaultSerializerProvider.Impl();
    sp.setNullValueSerializer(new NullSerializer());
    this.setSerializerProvider(sp);
  }
}

or specify it for some property using @JsonSerialize annotation, e.g:

public class MyClass {

  @JsonSerialize(nullsUsing = NullSerializer.class)
  private String property;
}
like image 120
Narendra Reddy Avatar answered Sep 28 '22 16:09

Narendra Reddy