### 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.=true|false`| |`com.fasterxml.jackson.core.JsonGenerator.Feature`|`spring.jackson.generator.=true|false`| |`com.fasterxml.jackson.databind.MapperFeature`|`spring.jackson.mapper.=true|false`| |`com.fasterxml.jackson.core.JsonParser.Feature`|`spring.jackson.parser.=true|false`| |`com.fasterxml.jackson.databind.SerializationFeature`|`spring.jackson.serialization.=true|false`| 例如,设置`spring.jackson.serialization.indent_output=true`可以开启漂亮打印。注意,由于[松绑定](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config-relaxed-binding)的使用,`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”](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-customize-the-responsebody-rendering)和[WebMvcAutoConfiguration](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration.java)源码。