Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

java - How do you override the null serializer in Jackson 2.0?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...