Multiple ObjectMappers for different parts of API
If both parts of the API
are not dealing with the same domain objects, you'll be able to do it by providing your own implementation of MappingJackson2HttpMessageConverter
that overwrite the canRead
and canWrite
methods. Here an example using the base package of the object which must be serialized :
Custom converter :
public class CustomConverter extends MappingJackson2HttpMessageConverter {
private String basePackage;
public CustomConverter(String basePackage) {
this.basePackage = basePackage;
}
@Override
public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
if (contextClass.getName().startsWith(basePackage)) {
return super.canRead(type, contextClass, mediaType);
}
return false;
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
if (clazz.getName().startsWith(basePackage)) {
return super.canWrite(clazz, mediaType);
}
return false;
}
}
Configuration
@Configuration
public class Configuration {
@Bean
public MappingJackson2HttpMessageConverter camelCaseConverter() {
MappingJackson2HttpMessageConverter converter = new CustomConverter("package.camel");
converter.setObjectMapper(camelCaseObjectMapper());
return converter;
}
@Bean
public MappingJackson2HttpMessageConverter snakeCaseConverter() {
MappingJackson2HttpMessageConverter converter = new CustomConverter("package.snake");
converter.setObjectMapper(snakeCaseObjectMapper());
return converter;
}
@Bean
public ObjectMapper camelCaseObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE);
return mapper;
}
@Bean
public ObjectMapper snakeCaseObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
return mapper;
}
}