To serialize deserialize object I am useing Jackson as flow
@JsonSerialize(using = LocalDateSerializer.class)
@JsonDeserialize(using = LocalDateDeserializer.class)
private LocalDate openingDate
How do I make this the default globally so I do not have to add it to every property ?
Using XML configuration.
If you are using Java-based configuration, you can create your configuration class extending WebMvcConfigurerAdapter and do the following:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
converter.setObjectMapper(objectMapper);
converters.add(converter);
super.configureMessageConverters(converters);
}
In here, you can configure the ObjectMapper as you like and set it as a converter.
With Spring Boot you can achieve this by registering new Module
.
@Configuration
public class AppConfig {
@Bean
public Module module() {
SimpleModule module = new SimpleModule("Module", new Version(1, 0, 0, null, null, null));
module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
return module;
}
}
As stated in documentation here
Jackson 1.7 added ability to register serializers and deserializes via Module interface. This is the recommended way to add custom serializers -- all serializers are considered "generic", in that they are used for subtypes unless more specific binding is found.
and here:
Any beans of type
com.fasterxml.jackson.databind.Module
are automatically registered with the auto-configuredJackson2ObjectMapperBuilder
and are applied to anyObjectMapper
instances that it creates. This provides a global mechanism for contributing custom modules when you add new features to your application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With