How to customise the Jackson JSON mapper implicitly used by Spring Boot? - java

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/

Related

How to autowire by name instead of type [duplicate]

This question already has answers here:
Spring boot two object mapper bean
(3 answers)
What is a NoSuchBeanDefinitionException and how do I fix it?
(1 answer)
Closed 1 year ago.
I know I'm not the first to have this problem, but I'm struggling to create multiple beans of the same type in Spring Boot 2.5.4.
My config:
#Configuration
public class MapperConfig {
#Bean("yamlMapper")
public ObjectMapper yamlMapper() {
return new ObjectMapper(new YAMLFactory());
}
#Bean("jsonMapper")
public ObjectMapper jsonMapper() {
return new ObjectMapper();
}
}
And my service class:
#Service
#RequiredArgsConstructor
public class MapperService {
#Qualifier("jsonMapper")
private final ObjectMapper jsonMapper;
#Qualifier("yamlMapper")
private final ObjectMapper yamlMapper;
}
The error is as follows:
No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected single matching bean but found 2: yamlMapper,jsonMapper
I've tried the various combinations of #Bean, #Qualifier, etc. suggested in other SO posts and the docs, but I can't seem to find a way of making Spring autowire by name instead of type. Any help would be greatly appreciated!
SOLUTION:
As pointed out by Youssef, it's not the MapperService which is failing to find the right bean, it's Spring Boot's MappingJackson2HttpMessageConverterConfiguration class. We can't add annotations to that class, so need to resort to using #Primary in our config.
The context loads okay as follows:
#Configuration
public class MapperConfig {
#Bean
public ObjectMapper yamlMapper() {
return new ObjectMapper(new YAMLFactory());
}
#Bean
#Primary
public ObjectMapper jsonMapper() {
return new ObjectMapper();
}
}
#Service
#RequiredArgsConstructor
public class MapperService {
#Autowired
#Qualifier("jsonMapper")
private final ObjectMapper jsonMapper;
#Autowired
#Qualifier("yamlMapper")
private final ObjectMapper yamlMapper;
}
Use the annotation:
#Resource
https://www.baeldung.com/spring-annotations-resource-inject-autowire
Your service:
#Service
public class MapperService {
#Resource(name = "jsonMapper")
private final ObjectMapper jsonMapper;
#Resource(name = "yamlMapper")
private final ObjectMapper yamlMapper;
}
You need to add #Primary annotation to one of your ObjectMapper beans like that
#Primary
#Bean("jsonMapper")
Because if you are using Spring Boot, it is needed by Jackson when trying auto configuration:
Parameter 0 of method mappingJackson2HttpMessageConverter in org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration required a single bean, but 2 were found:
But be careful also to as #M.Deinum comment: could also break stuff as this will also (partially) disable auto configuration for the ObjectMapper

Spring-Boot: Jackson serialization configuration not respected

I am working with spring-boot 2.5.4 and trying to set default-property-inclusion=non_null globally, so that null values no longer show up in my spring web server's responses.
I have configured spring.jackson.default-property-inclusion=non_null in my project's application.yml as described in an earlier question.
spring:
jackson:
default-property-inclusion: non_null
Unfortunately, null-values are still included in my controller's output:
{
"enabled": true,
"name": "foo",
"subdomain": null,
"tenantId": null
}
What works however is if I add non-null directly to my dto:
#Data
#NoArgsConstructor
#JsonInclude(Include.NON_NULL)
public class GlobalTenantGet {
private UUID tenantId;
private String name;
private String subdomain;
private boolean enabled;
}
yielding
{
"enabled": true,
"name": "foo"
}
as expected.
question
Why does configuring #JsonInclude locally on the dto cause the null properties to disappear as expected but why does configuring spring.jackson.default-property-inclusion=non_null not have the same effect?
additional info
1. Debugging
Setting a breakpoint in org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration.JacksonObjectMapperConfiguration#jacksonObjectMapper shows, that the properties configured in application.yaml really made it to jackson:
2. Autowiring ObjectMapper in the controller
I get the expected behavior when autowiring the ObjectMapper in my controller and serializing my object directly via objectMapper.writeValueAsString().
other ways to configure the ObjectMapper
These are mostly in reply to Pawel Woroniecki's answer
1. Using #primary
I have a
#Configuration
public class ObjectMapperConfiguration {
#Primary
#Bean
public ObjectMapper objectMapper() {
final var om = new ObjectMapper();
om.setSerializationInclusion(Include.NON_NULL);
return om;
}
}
still includes null properties in the output
2. Jackson2ObjectMapperBuilder with serializationInclusion
#Configuration
public class ObjectMapperConfiguration {
#Bean
public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
return new Jackson2ObjectMapperBuilder().serializationInclusion(JsonInclude.Include.NON_NULL);
}
}
still yields
{
"enabled": true,
"name": "foo",
"subdomain": null,
"tenantId": null
}
3. define MappingJackson2HttpMessageConverter
#Configuration
public class ObjectMapperConfiguration {
#Bean
public MappingJackson2HttpMessageConverter messageMappingConverter() {
final var om = new ObjectMapper();
om.setSerializationInclusion(Include.NON_NULL);
return new MappingJackson2HttpMessageConverter(om);
}
}
still no bueno :-(
It seems #EnableWebMvc is the culprit. I have a WebMvcConfigurer that looks like this:
#Configuration
#EnableWebMvc // <----- this is the culprit!
public class WebConfiguration implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE")
.allowedOrigins("example.com")
.allowedHeaders("*");
}
#Bean
public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
#Bean
public InternalResourceViewResolver defaultViewResolver() {
return new InternalResourceViewResolver();
}
}
commenting out #EnableWebMvc allows everything to work as expected.
There are several possible approaches to solve this issue and some of them are clearly explained here: https://www.baeldung.com/spring-boot-customize-jackson-objectmapper
Generally you can:
Override default ObjectMapper by creating custom ObjectMapper bean and marking it as #Primary (the simplest way but heavily impacts your application as all ObjectMapper instances you inject in code will use this one by default which may be good or not for you)
Define custom bean for Jackson2ObjectMapperBuilder and set proper serializationInclusion on this builder.
Register custom HTTP message converter in Spring which will use custom ObjectMapper by defining bean for MappingJackson2HttpMessageConverter (constructor of this converter accepts ObjectMapper so you can pass properly configured mapper there)

How to inject different ObjectMappers having different configurations through Autowired?

I'm trying to have 2 different Jackson ObjectMappers so that I that I can switch between using either one of them in my code. The 2 ObjectMappers are going to have some slight differences in their configuration.
In my configuration file, I have them as 2 separate means this way:
#Configuration
public class ApplicationConfiguration {
private ObjectMapper createMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
// And a few more other common configurations
return mapper;
}
#Bean
#Qualifier("standardObjectMapper")
public ObjectMapper standardObjectMapper() {
ObjectMapper mapper = createMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Product.class, new StandardProductSerializer());
mapper.registerModule(module);
return mapper;
}
#Bean
#Qualifier("specialObjectMapper")
public ObjectMapper specialObjectMapper() {
ObjectMapper mapper = createMapper();
SimpleModule module = new SimpleModule();
// In this mapper, I have a different serializer for the Product class
module.addSerializer(Product.class, new SpecialProductSerializer());
mapper.registerModule(module);
return mapper;
}
}
My plan is to inject and use one of those mappers whenever I need them. So in my test, I have something like this:
class SerializationTest {
#Autowired
#Qualifier("standardObjectMapper")
private ObjectMapper standardObjectMapper;
#Autowired
#Qualifier("specialObjectMapper")
private ObjectMapper specialObjectMapper;
#Test
void testSerialization() throws JsonProcessingException {
Product myProduct = new Product("Test Product");
String stdJson = objectMapper.writeValueAsString(myProduct);
String specialJson = specialObjectMapper.writeValueAsString(myProduct);
// Both stdJson and specialJson are of the same value even though they should be different because the mappers have different serializers!
}
}
However, it seems that the 2 ObjectMappers, standardObjectMapper and specialObjectMapper both are using the same StandardProductSerializer.
I'm expecting the specialObjectMapper to use the SpecialProductSerializer but this isn't the case.
Shouldn't the 2 ObjectMappers be different? I assume the injection would be based on their individual names since their types are the same?
What should I do to fix the issue so that the 2 ObjectMappers can be using different Serializers?
Update:
I've tried using Qualifiers but I'm getting an error that the beans cannot be found:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.site.SerializationTest': Unsatisfied dependency expressed through field 'standardObjectMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true), #org.springframework.beans.factory.annotation.Qualifier(value="standardObjectMapper")}
Add #Qualifier should resolve your problem
#Bean
#Qualifier("standardMapper")
public ObjectMapper standardObjectMapper() {
ObjectMapper mapper = createMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Product.class, new StandardProductSerializer());
mapper.registerModule(module);
return mapper;
}
#Bean
#Qualifier("specialMapper")
public ObjectMapper specialObjectMapper() {
ObjectMapper mapper = createMapper();
SimpleModule module = new SimpleModule();
// In this mapper, I have a different serializer for the Product class
module.addSerializer(Product.class, new SpecialProductSerializer());
mapper.registerModule(module);
return mapper;
}
Then add #Qualifier with your #Autowired
#Autowired
#Qualifier("standardMapper")
private ObjectMapper standardObjectMapper;
#Autowired
#Qualifier("specialMapper")
private ObjectMapper specialObjectMapper;
You can use the #Qualifier annotation in order to distinguish the different istances of ObjectMapper. (see: https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-autowired-annotation-qualifiers)
#Qualifier("objectMapper1")
#Autowired
private ObjectMapper objMapper1;
could you please try this, it will inject bean based on name
#Autowired
#Qualifier("standardObjectMapper")
private ObjectMapper standardObjectMapper;
#Autowired
#Qualifier("specialObjectMapper")
private ObjectMapper specialObjectMapper;
hope this will work for you
You can use #Qualifier annotation:
#Qualifier("specialObjectMapper")
#Autowired
private ObjectMapper specialObjectMapper;
#Qualifier("standardMapper")
#Autowired
private ObjectMapper standardObjectMapper;
The problem is that the #Configuration-class is not scanned during DI startup. Normally, spring looks for configuration from the package the Application class (annotated with #SpringBootApplication) resides.
I would suggest moving the #Configuration class in a sub-package of that in which the #SpringBootApplication resides.
There are other ways (e.g. this one described at baelung) to change the root-package for component scanning. I would, however, not recommend doing this unless all other options have been exhausted.

How to declare another Jackson ObjectMapper without affecting 'clients' of the original bean?

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.

How to customise Jackson in Spring Boot 1.4

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();
}

Categories