Spring Message Converter
MappingJackson2HttpMessageConverter
An HttpMessageConverter implementation that can read and write JSON using Jackson’s ObjectMapper. JSON mapping can be customized as needed through the use of Jackson’s provided annotations. When further control is needed, a custom ObjectMapper can be injected through the ObjectMapper property for cases where custom JSON serializers/deserializers need to be provided for specific types. By default this converter supports ( application/json).
22.16.12 Message Converters
Customization of HttpMessageConverter can be achieved in Java config by overriding configureMessageConverters() if you want to replace the default converters created by Spring MVC, or by overriding extendMessageConverters() if you just want to customize them or add additional converters to the default ones.
Below is an example that adds Jackson JSON and XML converters with a customized ObjectMapper instead of default ones:
@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
.indentOutput(true)
.dateFormat(new SimpleDateFormat("yyyy-MM-dd"))
.modulesToInstall(new ParameterNamesModule());
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
converters.add(new MappingJackson2XmlHttpMessageConverter(builder.xml().build()));
}
}
In this example, Jackson2ObjectMapperBuilder is used to create a common configuration for both MappingJackson2HttpMessageConverter and MappingJackson2XmlHttpMessageConverter with indentation enabled, a customized date format and the registration of jackson-module-parameter-names that adds support for accessing parameter names (feature added in Java 8).
![]() |
| Enabling indentation with Jackson XML support requires |
Other interesting Jackson modules are available:
- jackson-datatype-money: support for
javax.moneytypes (unofficial module) - jackson-datatype-hibernate: support for Hibernate specific types and properties (including lazy-loading aspects)

本文介绍如何在Spring MVC中使用Jackson库自定义HTTP消息转换器,包括JSON和XML格式的支持。通过覆盖configureMessageConverters方法,可以替换默认的转换器,并通过Jackson2ObjectMapperBuilder设置缩进输出、日期格式及模块安装,实现更精细的控制。
![[Note]](https://i-blog.csdnimg.cn/blog_migrate/7694cf0866ae229da7b27adaede047f8.png)
458

被折叠的 条评论
为什么被折叠?



