Use JsonSerialize for java types at class level

Viewed 133

I have a class Response with multiple Double values in it. It looks something like below.

class Data {
   private Double number1;
   private Double number2;
   private Double number3;
   private Double number4;

   //Getters and Setters ... 

}

I want use this class to send a response for a Spring rest service, however I need to format the Double values in a specific way (something like 23,45,276.10 ).

I can achieve this by changing the types to String and setting them via java.text.DecimalFormat or via using JsonSerialize annotation at each field.

But is there a way where I can define this at class level, or better yet at request level? Annotating every single Double variable is something I would want to avoid.

Like some kind of global or class level configuration/annotation that can help me convert all Double elements into a specific format?

1 Answers

You can programmatically register your serializer as follows:

@Configuration
public class JacksonConfiguration {

    @Bean
    public ObjectMapper serializingObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();

        SimpleModule module = new SimpleModule();
        module.addSerializer(Double.class, new YourDoubleSerializer());
        objectMapper.registerModule(module);

        return objectMapper;
    }

}

This would be applied to all Double properties in your classes when they are serialized. Doing this at the request level I don't think it is possible.

Related