Chanandler Bong
Chanandler Bong

Reputation: 518

Simple way to serialize nulls as zeroes in Jackson

Part of my response are some BigDecimal fields and I would like to serialize these specific fields to 0 when they are null. Is there a simple way in Jackson library to achieve that (i.e. with field annotation or something similar) or is a custom serializer required here?

Upvotes: 0

Views: 861

Answers (1)

Vic
Vic

Reputation: 318

You need a custom serializer (try extending StdSerializer, NullSerializer has a private default constructor...).

If you want all null fields in class to be treated this way, you can simply annotate the target class:

@JsonSerialize(nullsUsing = NullsToZeroSerializer.class)

If you want to do it in the whole project, create a SimpleModule for ObjectMapper and add your serializer to this module, and the module to ObjectMapper.

If you want to do this only for BigDecimal it may be sufficient to simply check the value passed to serialize method with instanceof.

public class NullToZeroSerializer extends StdSerializer<Object> {

protected NullToZeroSerializer(Class<Object> t) {
    super(t);
}

@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
    if (value instanceof BigDecimal) {
        gen.writeNumber(0);
    } else {
        gen.writeNull();
    }
}

}

Upvotes: 1

Related Questions