spring_reference/IX. ‘How-to’ guides/65.3. Customize the Jackson...

3.0 KiB
Raw Permalink Blame History

65.3. 自定义Jackson ObjectMapper

在一个HTTP交互中Spring MVC客户端和服务端使用HttpMessageConverters协商内容转换。如果classpath下存在Jackson你就已经获取到Jackson2ObjectMapperBuilder提供的默认转换器。

创建的ObjectMapper或用于Jackson XML转换的XmlMapper实例默认有以下自定义属性

  • MapperFeature.DEFAULT_VIEW_INCLUSION禁用
  • DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES禁用

Spring Boot也有一些简化自定义该行为的特性。

你可以使用当前的environment配置ObjectMapper和XmlMapper实例。Jackson提供一个扩展套件可以用来简单的关闭或开启一些特性你可以用它们配置Jackson处理的不同方面。这些特性在Jackson中使用5个枚举进行描述的并被映射到environment的属性上

Jackson枚举 Environment属性
com.fasterxml.jackson.databind.DeserializationFeature `spring.jackson.deserialization.<feature_name>=true
com.fasterxml.jackson.core.JsonGenerator.Feature `spring.jackson.generator.<feature_name>=true
com.fasterxml.jackson.databind.MapperFeature `spring.jackson.mapper.<feature_name>=true
com.fasterxml.jackson.core.JsonParser.Feature `spring.jackson.parser.<feature_name>=true
com.fasterxml.jackson.databind.SerializationFeature `spring.jackson.serialization.<feature_name>=true

例如,设置spring.jackson.serialization.indent_output=true可以开启漂亮打印。注意,由于松绑定的使用,indent_output不必匹配对应的枚举常量INDENT_OUTPUT

如果想彻底替换默认的ObjectMapper你需要定义一个该类型的@Bean并将它标记为@Primary

定义一个Jackson2ObjectMapperBuilder类型的@Bean将允许你自定义默认的ObjectMapper和XmlMapper分别用于MappingJackson2HttpMessageConverter和MappingJackson2XmlHttpMessageConverter

另一种自定义Jackson的方法是向你的上下文添加com.fasterxml.jackson.databind.Module类型的beans。它们会被注册入每个ObjectMapper类型的bean当为你的应用添加新特性时这就提供了一种全局机制来贡献自定义模块。

最后如果你提供任何MappingJackson2HttpMessageConverter类型的@Beans那它们将替换MVC配置中的默认值。同时也提供一个HttpMessageConverters类型的bean它有一些有用的方法可以获取默认的和用户增强的message转换器。

想要获取更多细节可查看Section 65.4, “Customize the @ResponseBody rendering”WebMvcAutoConfiguration源码。