I've been unable to find examples of how to use Jackson2ObjectMapperBuilderCustomizer.java in spring boot 1.4 to customise the features of Jackson.
The doco for customising Jackson in boot 1.4 - https://docs.spring.io/spring-boot/docs/1.4.x/reference/htmlsingle/#howto-customize-the-jackson-objectmapper
My configuration works, although I am unsure if this is the correct way to customise the object mapper using Jackson2ObjectMapperBuilderCustomizer.java
#Configuration
public class JacksonAutoConfiguration {
#Autowired
private Environment env;
#Bean
public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder(
List<Jackson2ObjectMapperBuilderCustomizer> customizers) {
Jackson2ObjectMapperBuilder builder = configureObjectMapper();
customize(builder, customizers);
return builder;
}
private void customize(Jackson2ObjectMapperBuilder builder,
List<Jackson2ObjectMapperBuilderCustomizer> customizers) {
for (Jackson2ObjectMapperBuilderCustomizer customizer : customizers) {
customizer.customize(builder);
}
}
private Jackson2ObjectMapperBuilder configureObjectMapper() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
List<String> activeProfiles = asList(env.getActiveProfiles());
if (activeProfiles.contains(SPRING_PROFILE_DEVELOPMENT)) {
builder.featuresToEnable(SerializationFeature.INDENT_OUTPUT);
}
return builder;
}
}
To provide some context, this class sits in my own spring starter project for REST services that just auto configures a number of things, like ControllerAdvice and some trivial features like the above.
So my goal is to extend the Jackson configuration rather than to override any configuration provided by boot or other packages.
To customize the Jackson ObjectMapper that's already pre-configured by Spring Boot, I was able to do this (the example here is to add a custom deserializer).
Configuration class:
#SpringBootConfiguration
public class Application {
#Autowired
private BigDecimalDeserializer bigDecimalDeserializer;
...
#Bean
public Jackson2ObjectMapperBuilderCustomizer addCustomBigDecimalDeserialization() {
return new Jackson2ObjectMapperBuilderCustomizer() {
#Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.deserializerByType(BigDecimal.class, bigDecimalDeserializer);
}
};
}
...
}
And my custom deserializer, to show how it's picked up by Spring:
#Component
public class BigDecimalDeserializer extends StdDeserializer<BigDecimal> {
public BigDecimalDeserializer() {
super(BigDecimal.class);
}
#Override
public BigDecimal deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
...
}
...
}
It depends on what you're trying to do.
If you want to make some customisations in addition to those that are performed by default then you should create your own Jackson2ObjectMapperBuilderCustomizer implementation and expose it as a bean. What you currently have is a more complex version of this. Rather than having the customisers injected and then calling them yourself, you can just create your own customiser bean and Boot will call it for you.
If you want to take complete control and switch off all of Boot's customisations then create a Jackson2ObjectMapperBuilder or ObjectMapper bean and configure it as required. The builder approach is preferred as this builder is then also used to configure ObjectMappers created by other components such as Spring Data REST.
Looking at your code and taking a step back, you could configure things far more simply by using a profile-specific configuration file (something like application-dev.properties) to enable indenting of Jackson's output. You can read more about that here.
just create an ObjectMapper bean:
#Bean
ObjectMapper objectMapper() {
return Jackson2ObjectMapperBuilder
.json()
.featuresToEnable(MapperFeature.DEFAULT_VIEW_INCLUSION)
.build();
}
Related
I want to configure Hibernate to use Jackson's Objectmapper created by Spring to map between json and entities. In the project I'm working on I already configured Jooq to use the Spring's ObjectMapper but I'm having trouble how to configure Hibernate to use it. The goal in the end is that both Jooq and Hibernate would use the same ObjectMapper.
I checked this article by Vlad. Unfortunately all the tips given in the article don't work for the project I'm working on.
Here's an example configuration I tried
#Configuration
public class HibernateConfiguration implements HibernatePropertiesCustomizer {
//Autowire Objectmapper created by Spring
#Autowired
ObjectMapper objectMapper;
#Override
public void customize(Map<String, Object> hibernateProperties) {
ObjectMapperSupplier objectMapperSupplier = () -> objectMapper;
// Below config doesn't work since Hibernate types creates it's own mapper
hibernateProperties.put("hibernate.types.jackson.object.mapper", objectMapperSupplier);
}
Also tried the same approach by adding the Objectmapper to hibernate-types.properties.
#Used by Hibernate but cannot get reference of Spring managed ObjectMapper since this is class is called outside of Spring's context.
hibernate.types.jackson.object.mapper=path.to.ObjectMapperSupplier
Another approach I used but it fails with a NullpointerException when converting from JSON to an entity in JsonTypeDescriptor class.
#Configuration
public class HibernateConfiguration implements HibernatePropertiesCustomizer{
#Autowired
ObjectMapper objectMapper;
#Override
public void customize(Map<String, Object> hibernateProperties) {
// Underlying implementation needs some JavaType or propertyClass, otherwise when converting
// from JSON we get a nullpointer.
var jsonBinaryType = new JsonBinaryType(objectMapper);
hibernateProperties.put("hibernate.type_contributors", (TypeContributorList) () ->
Collections.singletonList((typeContributions, serviceRegistry) ->
typeContributions.contributeType(jsonBinaryType)));
}
Below is the type declaration for entity super class.
// This makes Hibernate types create it's own mapper.
#TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
#MappedSuperclass
public abstract class Entity{
}
So, are there any possible solutions how I can hook up Spring managed ObjectMapper to Hibernate?
I finally figured this out, but it is kind of an creative solution...
TLDR: I have a bean that stores the Spring-configured objectMapper in a static field. A BeanFactoryPostProcessor ensures that this bean is initialized before Hibernate (types) tries to load / get the ObjectMapper.
hibernate.properties
hibernate.types.jackson.object.mapper=com.github.lion7.example.HibernateObjectMapperSupplier
HibernateObjectMapperSupplier.kt
package com.github.lion7.example
import com.fasterxml.jackson.databind.ObjectMapper
import com.vladmihalcea.hibernate.type.util.ObjectMapperSupplier
import org.springframework.beans.factory.config.BeanFactoryPostProcessor
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory
import org.springframework.stereotype.Component
class HibernateObjectMapperSupplier : ObjectMapperSupplier {
override fun get(): ObjectMapper =
ObjectMapperHolder.objectMapper
}
#Component
class ObjectMapperHolder(objectMapper: ObjectMapper) {
companion object {
lateinit var objectMapper: ObjectMapper
}
init {
Companion.objectMapper = objectMapper
}
}
#Component
class ObjectMapperDependencyFixer : BeanFactoryPostProcessor {
override fun postProcessBeanFactory(beanFactory: ConfigurableListableBeanFactory) {
val beanDefinition = beanFactory.getBeanDefinition("entityManagerFactory")
val oldDependsOn = beanDefinition.dependsOn ?: emptyArray()
val newDependsOn = oldDependsOn + "objectMapperHolder"
beanDefinition.setDependsOn(*newDependsOn)
}
}
Same code as gist: https://gist.github.com/lion7/c8006b69a309e38183deb69124b888b5
A Java implementation.
#Component
public class HibernateObjectMapper implements Supplier<ObjectMapper> {
private static ObjectMapper objectMapper;
#Autowired
public void setObjectMapper(ObjectMapper objectMapper) {
HibernateObjectMapper.objectMapper = objectMapper;
}
#Override
public ObjectMapper get() {
return objectMapper;
}
}
If you define your own JPA beans, simply add #DependsOn("hibernateObjectMapper") to their config. Otherwise you need a BeanPostProcessor to add the dependency to the autoconfigured bean:
#Component
class HibernateBeanDependencyProcessor implements BeanFactoryPostProcessor {
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) {
BeanDefinition beanDefinition = factory.getBeanDefinition("entityManagerFactory");
String[] dependsOn = beanDefinition.getDependsOn();
dependsOn = dependsOn == null ? new String[]{} : dependsOn;
String[] newDependsOn = new String[dependsOn.length + 1];
System.arraycopy(dependsOn, 0, newDependsOn, 1, dependsOn.length);
newDependsOn[0] = "hibernateObjectMapper";
beanDefinition.setDependsOn(newDependsOn);
}
}
As for the property, hibernate.types.* don't work when set programmatically. The library looks directly in the hibernate.properties, hibernate-types.properties, and application.properties files.
I think that I've found solution to do it programmatically (without magic with fixing dependency graph).
HibernateConfiguration.kt
#Configuration(proxyBeanMethods = false)
class HibernateConfiguration {
#Bean
fun hibernatePropertiesCustomizer(
objectMapper: ObjectMapper // Thanks to that Spring can create correct dependency graph
): HibernatePropertiesCustomizer =
HibernatePropertiesCustomizer { hibernateProperties ->
HibernateObjectMapperSupplier.objectMapper = objectMapper
hibernateProperties["hibernate.types.jackson.object.mapper"] = HibernateObjectMapperSupplier::class.qualifiedName
}
}
HibernateObjectMapperSupplier.kt
class HibernateObjectMapperSupplier : Supplier<ObjectMapper> {
override fun get(): ObjectMapper {
return objectMapper
}
companion object {
lateinit var objectMapper: ObjectMapper
}
}
System.getProperties().put(
Configuration.PropertyKey.JACKSON_OBJECT_MAPPER.getKey(),
MyObjectMapperSupplier.class.getName()
);
I have multiple library classes in my project which need to be injected into a service class. This is the error statement for IntegrationFactory class:
Consider defining a bean of type 'com.ignitionone.service.programmanager.integration.IntegrationFactory' in your configuration.
This error is coming on almost every injection where this library class is injected.
I have already added the Library package in #ComponentScan, but, as it is read-only file, I can not annotate the library class. I came to know from some answer here that Spring can not inject classes which it does not manage. This library is not built on spring.
I have tried to create a #Bean method which returns the IntegrationFactory(class in question) in the class where #Inject is used, but this too does not seem to work.
How can this be done, preferably without creating a stub/copy class?
This is EngagementServiceImpl class snippet:
#Inject
public EngagementServiceImpl(EngagementRepository engagementRepository,
#Lazy IntegrationFactory integrationFactory, TokenRepository tokenRepository,
EngagementPartnerRepository engagementPartnerRepository, MetricsService metricsService) {
this.engagementRepository = engagementRepository;
this.integrationFactory = integrationFactory;
this.tokenRepository = tokenRepository;
this.engagementPartnerRepository = engagementPartnerRepository;
this.metricsService = metricsService;
}
This is injection part:
#Autowired
private EngagementService engagementService;
This is ConfigClass:
#Configuration
public class ConfigClass {
#Bean
public IntegrationFactory getIntegrationFactory(){
Map<String, Object> globalConfig = new HashMap<>();
return new IntegrationFactory(globalConfig);
}
#Bean
#Primary
public EntityDataStore getEntityDataStore(){
EntityModel entityModel = Models.ENTITY;
return new EntityDataStore(this.dataSource(), entityModel );
}
#ConfigurationProperties(prefix = "datasource.postgres")
#Bean
#Primary
public DataSource dataSource() {
return DataSourceBuilder
.create()
.build();
}
}
You need to add your bean definitions in a configuration class.
#Configuration
public class ServiceConfig {
#Bean
public IntegrationFactory getIntegrationFactory(){
// return an IntegrationFactory instance
}
}
Then you have to make sure your #Configuration class gets detected by Spring, either by having it within your scanned path or by manually importing it via #Import from somewhere withing you scanned path. An example of #Import, considering you are using Spring Boot.
#Import(ServiceConfig.class)
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Hope this helps!
Your Bean IntegrationFactory can't be found, as it is not annotated with any Spring stereotype and therefore not recognized by the component scan.
As you have multiple options to provide an instance of your class to the application context, read the Spring documentation (which also includes samples) to find out which one fits you the most:
https://docs.spring.io/spring/docs/5.1.0.RELEASE/spring-framework-reference/core.html#beans-java-basic-concepts
One Option would be to create a factory which provides an instance of your class to the application context, like it is stated in the documentation:
#Configuration
public class AppConfig {
#Bean
public IntegrationFactory myIntegrationFactory() {
return new IntegrationFactory();
}
}
Do not forget to add the Configuration to the application context.
I have a spring-boot application that exposes a json REST API. For mapping objects to json it uses the built-in jackson ObjectMapper configured by spring-boot.
Now I need to read some data from a yaml file and I found that an easy way to do it is using Jackson - for this I need to declare a different ObjectMapper to convert yaml to objects. I declared this new mapper bean with a specific name to be able to inject it in my service dealing with reading from the yaml file:
#Bean(YAML_OBJECT_MAPPER_BEAN_ID)
public ObjectMapper yamlObjectMapper() {
return new ObjectMapper(new YAMLFactory());
}
But I need a way to tell all the other "clients" of the original json ObjectMapper to keep using that bean. So basically I would need a #Primary annotation on the original bean. Is there a way to achieve this without having to redeclare the original ObjectMapper in my own configuration (I'd have to dig through spring-boot code to find and copy its configuration)?
One solution I found is to declare a FactoryBean for ObjectMapper and make it return the already declared bean, as suggested in this answer. I found by debugging that my original bean is called "_halObjectMapper", so my factoryBean will search for this bean and return it:
public class ObjectMapperFactory implements FactoryBean<ObjectMapper> {
ListableBeanFactory beanFactory;
public ObjectMapper getObject() {
return beanFactory.getBean("_halObjectMapper", ObjectMapper.class);
}
...
}
Then in my Configuration class I declare it as a #Primary bean to make sure it's the first choice for autowiring:
#Primary
#Bean
public ObjectMapperFactory objectMapperFactory(ListableBeanFactory beanFactory) {
return new ObjectMapperFactory(beanFactory);
}
Still, I'm not 100% happy with this solution because it relies on the name of the bean which is not under my control, and it also seems like a hack. Is there a cleaner solution?
Thanks!
You can define two ObjectMapper beans and declare one as primary, e.g.:
#Bean("Your_id")
public ObjectMapper yamlObjectMapper() {
return new ObjectMapper(new YAMLFactory());
}
#Bean
#Primary
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
Once done, you can use your objectmapper bean with #Qualifier annotation, e.g.:
#Autowired
#Qualifier("Your_id")
private ObjectMapper yamlMapper;
Update
You can dynamically add your ObjectMapper to Spring's bean factory at runtime, e.g.:
#Configuration
public class ObjectMapperConfig {
#Autowired
private ConfigurableApplicationContext context;
#PostConstruct
private void init(){
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(ObjectMapper.class);
builder.addConstructorArgValue(new JsonFactory());
DefaultListableBeanFactory factory = (DefaultListableBeanFactory) context.getBeanFactory();
factory.registerBeanDefinition("yamlMapper", builder.getBeanDefinition());
Map<String, ObjectMapper> beans = context.getBeansOfType(ObjectMapper.class);
beans.entrySet().forEach(System.out::println);
}
}
The above code adds a new bean into context without changing the existing bean (sysout prints two beans in the end of init method). You can then use "yamlMapper" as qualifier to autowire it anywhere.
Update 2 (from question author):
The solution suggested in 'Update' works and here's a simplified version:
#Autowired
private DefaultListableBeanFactory beanFactory;
#PostConstruct
private void init(){
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(YAMLMapper.class);
beanFactory.registerBeanDefinition("yamlMapper", builder.getBeanDefinition());
}
Other option is to wrap custom mapper into custom object:
#Component
public class YamlObjectMapper {
private final ObjectMapper objectMapper;
public YamlObjectMapper() {
objectMapper = new ObjectMapper(new YAMLFactory());
}
public ObjectMapper getMapper() {
return objectMapper;
}
}
Unfortunately this approach requires calling getMapper after you inject YamlObjectMapper.
I believe defining explicit primary object mapper for MVC layer should work this way:
#Primary
#Bean
public ObjectMapper objectMapper() {
return Jackson2ObjectMapperBuilder.json().build();
}
All beans that autowire object mapper via type will use above bean. Your Yaml logic can autowire via YAML_OBJECT_MAPPER_BEAN_ID.
I just realized that I don't need to use a FactoryBean, I could just as well declare a regular bean as #Primary and make it return the original bean, like this:
#Bean
#Primary
public ObjectMapper objectMapper(#Qualifier("_halObjectMapper") ObjectMapper objectMapper) {
return objectMapper;
}
This makes the configuration slightly cleaner, but still requires the exact name of the original ObjectMapper. I guess I'll stay with this solution, though.
I have a test instantiating some entities, saving them to MongoDB and loading them again to make sure the mapping works corretly. I'd like to use the #DataMongoTest annotation on the test class to make sure an embedded MongoDB instance is dynamically created.
This worked just fine until I had to introduce custom converters (org.springframework.core.convert.converter.Converter) for some classes. These are set up like this:
#ReadingConverter
public class MyClassReadConverter implements Converter<Document, MyClass> {
...
#WritingConverter
public class MyClassWriteConverter implements Converter<MyClass, Document> {
...
#Configuration
public class SpringMongoSetup extends AbstractMongoConfiguration {
#Override
public Mongo mongo() throws Exception {
//I don't want that in the test..
return new MongoClient("localhost");
}
#Override
public CustomConversions customConversions() {
// ..but I need this
List<Converter<?,?>> converters = new ArrayList<>();
converters.add(new MyClassWriteConverter());
converters.add(new MyClassReadConverter());
return new CustomConversions(converters);
}
...
For normal (non-test) execution this works just fine. The test also works if I use the #SpringBootTest annotation which makes the test use my configuration. Unfortunately, this configuration also defines the host/port for MongoDB, but I'd like to use the host/port of the embedded MongoDB started by #DataMongoTest.
Can I somehow configure it so that either #DataMongoTest uses the custom converters with the embedded MongoDB, or that I can get the embedded host/port while instantiating my configuration class?
To use CustomConverters with #DataMongoTest you need to expose those converters as a Spring bean, e.g.:
#Configuration
public class CustomConversionsConfiguration {
#Bean
public CustomConversions customConversions() {
List<Converter<?,?>> converters = new ArrayList<>();
converters.add(new MyClassWriteConverter());
converters.add(new MyClassReadConverter());
return new CustomConversions(converters);
}
}
...and use the configuration in Mongo test classes:
#RunWith(SpringRunner.class)
#DataMongoTest
#Import(CustomConversionsConfiguration.class)
public class MyMongoTest { ... }
If you are using slicing we will disable all scanning that isn't relevant to Mongo. We have no way to know that your SpringMongoSetup is related to Mongo so, since we don't scan it, it's not applied.
If you do not rely on the auto-configuration for Mongo, you'll have to import that class yourself. You can do so with #Import, e.g.
#RunWith(SpringRunner.class)
#DataMongoTest
#Import(SpringMongoSetup.class)
public class MyMongoTest { ... }
I'm using Spring Boot (1.2.1), in a similar fashion as in their Building a RESTful Web Service tutorial:
#RestController
public class EventController {
#RequestMapping("/events/all")
EventList events() {
return proxyService.getAllEvents();
}
}
So above, Spring MVC implicitly uses Jackson for serialising my EventList object into JSON.
But I want to do some simple customisations to the JSON format, such as:
setSerializationInclusion(JsonInclude.Include.NON_NULL)
Question is, what is the simplest way to customise the implicit JSON mapper?
I tried the approach in this blog post, creating a CustomObjectMapper and so on, but the step 3, "Register classes in the Spring context", fails:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'jacksonFix': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire method: public void com.acme.project.JacksonFix.setAnnotationMethodHandlerAdapter(org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter);
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter]
found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
It looks like those instructions are for older versions of Spring MVC, while I'm looking for a simple way to get this working with latest Spring Boot.
You can configure property inclusion, and numerous other settings, via application.properties:
spring.jackson.default-property-inclusion=non_null
There's a table in the documentation that lists all of the properties that can be used.
If you want more control, you can also customize Spring Boot's configuration programatically using a Jackson2ObjectMapperBuilderCustomizer bean, as described in the documentation:
The context’s Jackson2ObjectMapperBuilder can be customized by one or more Jackson2ObjectMapperBuilderCustomizer beans. Such customizer beans can be ordered (Boot’s own customizer has an order of 0), letting additional customization be applied both before and after Boot’s customization.
Lastly, if you don't want any of Boot's configuration and want to take complete control over how the ObjectMapper is configured, declare your own Jackson2ObjectMapperBuilder bean:
#Bean
Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
// Configure the builder to suit your needs
return builder;
}
I am answering bit late to this question, but someone, in future, might find this useful. The below approach, besides lots of other approaches, works best, and I personally think would better suit a web application.
#Configuration
#EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {
... other configurations
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.propertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
builder.serializationInclusion(Include.NON_EMPTY);
builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
converters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
}
}
A lot of things can configured in applicationproperties. Unfortunately this feature only in Version 1.3, but you can add in a Config-Class
#Autowired(required = true)
public void configureJackson(ObjectMapper jackson2ObjectMapper) {
jackson2ObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
[UPDATE: You must work on the ObjectMapper because the build()-method is called before the config is runs.]
The documentation states several ways to do this.
If you want to replace the default ObjectMapper completely, define a #Bean of that type and mark it as #Primary.
Defining a #Bean of type Jackson2ObjectMapperBuilder will allow you to customize both default ObjectMapper and XmlMapper (used in MappingJackson2HttpMessageConverter and MappingJackson2XmlHttpMessageConverter respectively).
You can add a following method inside your bootstrap class which is annotated with #SpringBootApplication
#Bean
#Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
objectMapper.registerModule(new JodaModule());
return objectMapper;
}
spring.jackson.serialization-inclusion=non_null used to work for us
But when we upgraded spring boot version to 1.4.2.RELEASE or higher, it stopped working.
Now, another property spring.jackson.default-property-inclusion=non_null is doing the magic.
in fact, serialization-inclusion is deprecated. This is what my intellij throws at me.
Deprecated: ObjectMapper.setSerializationInclusion was deprecated in
Jackson 2.7
So, start using spring.jackson.default-property-inclusion=non_null instead
I stumbled upon another solution, which is quite nice.
Basically, only do step 2 from the blog posted mentioned, and define a custom ObjectMapper as a Spring #Component. (Things started working when I just removed all the AnnotationMethodHandlerAdapter stuff from step 3.)
#Component
#Primary
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
setSerializationInclusion(JsonInclude.Include.NON_NULL);
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
}
Works as long as the component is in a package scanned by Spring. (Using #Primary is not mandatory in my case, but why not make things explicit.)
For me there are two benefits compared to the other approach:
This is simpler; I can just extend a class from Jackson and don't need to know about highly Spring-specific stuff like Jackson2ObjectMapperBuilder.
I want to use the same Jackson configs for deserialising JSON in another part of my app, and this way it's very simple: new CustomObjectMapper() instead of new ObjectMapper().
When I tried to make ObjectMapper primary in spring boot 2.0.6 I got errors
So I modified the one that spring boot created for me
Also see https://stackoverflow.com/a/48519868/255139
#Lazy
#Autowired
ObjectMapper mapper;
#PostConstruct
public ObjectMapper configureMapper() {
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, true);
mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
SimpleModule module = new SimpleModule();
module.addDeserializer(LocalDate.class, new LocalDateDeserializer());
module.addSerializer(LocalDate.class, new LocalDateSerializer());
mapper.registerModule(module);
return mapper;
}
The right way to add further configurations to the Spring Boot peconfigured ObjectMapper is to define a Jackson2ObjectMapperBuilderCustomizer. Else you are overwriting Springs configuration, which you do not want to lose.
#Configuration
public class MyJacksonConfigurer implements Jackson2ObjectMapperBuilderCustomizer {
#Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.deserializerByType(LocalDate.class, new MyOwnJsonLocalDateTimeDeserializer());
}
}
I found the solution described above with :
spring.jackson.serialization-inclusion=non_null
To only work starting at the 1.4.0.RELEASE version of spring boot. In all other cases the config is ignored.
I verified this by experimenting with a modification of the spring boot sample "spring-boot-sample-jersey"
I've seen numerous questions regarding this issue. This is what worked for me in Spring Boot version 2.7.0-SNAPSHOT.
I created a configuration, MapperConfigs, created a objectMapper bean, annotated primary as the documentation says
#Configuration
#Log4j2
public class MapperConfigs {
#Bean
#Primary
ObjectMapper objectMapper() {
log.info("Object mapper overrides ");
return JsonMapper.builder()
.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
}
}
I then #Autowired objectMapper. See below:
#Service
public class GenerateRequestUniqueID {
#Autowired
ObjectMapper objectMapper;
...
}
I know the question asking for Spring boot, but I believe lot of people looking for how to do this in non Spring boot, like me searching almost whole day.
Above Spring 4, there is no need to configure MappingJacksonHttpMessageConverter if you only intend to configure ObjectMapper.
You just need to do:
public class MyObjectMapper extends ObjectMapper {
private static final long serialVersionUID = 4219938065516862637L;
public MyObjectMapper() {
super();
enable(SerializationFeature.INDENT_OUTPUT);
}
}
And in your Spring configuration, create this bean:
#Bean
public MyObjectMapper myObjectMapper() {
return new MyObjectMapper();
}
Remove the default one and add your custom converter:
#EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
#Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// Remove the default MappingJackson2HttpMessageConverter
converters.removeIf(converter -> {
String converterName = converter.getClass().getSimpleName();
return converterName.equals("MappingJackson2HttpMessageConverter");
});
// Add your custom MappingJackson2HttpMessageConverter
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
converter.setObjectMapper(objectMapper);
converters.add(converter);
WebMvcConfigurer.super.extendMessageConverters(converters);
}
}
Note: Please don't use configureMessageConverters() instead of extendMessageConverters() from WebMvcConfigurer because configure method will remove all the existing converters which will be installed by default.
Hope it will help someone like me who has wasted some hours debugging the issue :)
There are two ways to customize Jackson ObjectMapper:-
Override the default behavior of auto-configured ObjectMapper by Spring Boot
Overwrite the ObjectMapper to have a complete control
Override ObjectMapper
#Configuration
public class CustomJacksonConfig {
#Bean
#Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
return builder.build().setSerializationInclusion(JsonInclude.Include.NON_NULL)
.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(SerializationFeature.INDENT_OUTPUT, true)
.registerModule(new JavaTimeModule());
}
}
Overwrite ObjectMapper
#Configuration
public class CustomJacksonConfig {
#Bean
#Primary
public ObjectMapper objectMapper() {
return new ObjectMapper()
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(SerializationFeature.INDENT_OUTPUT, true);
}
}
source: https://codingnconcepts.com/spring-boot/customize-jackson-json-mapper/