Shahid Ghafoor
Shahid Ghafoor

Reputation: 3103

json serializer with spring boot

I have BigDecimalSerializer

public class BigDecimalSerializer extends JsonSerializer<BigDecimal> {

@Override
public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers)
  throws IOException {
gen.writeString(value.setScale(6, BigDecimal.ROUND_HALF_UP).toString());
}
}

and then

 @JsonSerialize(using = BigDecimalSerializer.class)
 private BigDecimal foo;

is there any way that instead of doing annotate in each member variable, I tell the spring boot at once that apply to all project ?

Upvotes: 0

Views: 671

Answers (1)

msp
msp

Reputation: 3364

Try configuring the ObjectMapper by adding a custom module. In case you're using spring-data-rest this can look like this:

@Configuration
public static class ObjectMapperConfigurer extends RepositoryRestConfigurerAdapter {
    @Override
    public void configureJacksonObjectMapper(final ObjectMapper objectMapper) {
        SimpleModule myModule = new SimpleModule();
        myModule.addSerializer(BigDecimal.class, BigDecimalSerializer.class);           
        objectMapper.registerModule(myModule));
    }
}

Otherwise simply provide your own ObjectMapper bean and configure it on creation.

Upvotes: 1

Related Questions