# 76.3 自定义Jackson ObjectMapper

在一个HTTP交互中，Spring MVC（客户端和服务端）使用`HttpMessageConverters`协商内容转换。如果classpath下存在Jackson，你就获取到`Jackson2ObjectMapperBuilder`提供的默认转换器，这是Spring Boot为你自动配置的实例。

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

* `MapperFeature.DEFAULT_VIEW_INCLUSION`，默认是禁用的
* `DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES`，默认是禁用的
* `SerializationFeature.WRITE_DATES_AS_TIMESTAMPS`，默认是禁用的

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

你可以使用当前的environment配置`ObjectMapper`和`XmlMapper`实例。Jackson提供一个扩展套件，可以用来关闭或开启一些特性，你可以用它们配置Jackson以处理不同方面。这些特性在Jackson中是使用6个枚举进行描述的，并被映射到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\`   |             |              |              |
| `com.fasterxml.jackson.annotation.JsonInclude.Include`  | \`spring.jackson.serialization-inclusion=always | non\_null | non\_absent | non\_default | non\_empty\` |

例如，设置`spring.jackson.serialization.indent_output=true`可以美化打印输出（pretty print）。注意，由于[松散绑定](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#boot-features-external-config-relaxed-binding)的使用，`indent_output`不必匹配对应的枚举常量`INDENT_OUTPUT`。

基于environment的配置会应用到自动配置的`Jackson2ObjectMapperBuilder` bean，然后应用到通过该builder创建的mappers，包括自动配置的`ObjectMapper` bean。

`ApplicationContext`中的`Jackson2ObjectMapperBuilder`可以通过`Jackson2ObjectMapperBuilderCustomizer` bean自定义。这些customizer beans可以排序（Spring Boot自己的customizer序号为0）。其他自定义可以应用到Spring Boot自定义之前或之后。

所有类型为`com.fasterxml.jackson.databind.Module`的beans都会自动注册到自动配置的`Jackson2ObjectMapperBuilder`，并应用到它创建的任何`ObjectMapper`实例。这提供了一种全局机制，用于在为应用添加新特性时贡献自定义模块。

如果想完全替换默认的`ObjectMapper`，你既可以定义该类型的`@Bean`并注解`@Primary`，也可以定义`Jackson2ObjectMapperBuilder` `@Bean`，通过builder构建。注意不管哪种方式都会禁用所有的自动配置`ObjectMapper`。

如果你提供`MappingJackson2HttpMessageConverter`类型的`@Bean`，它们将替换MVC配置中的默认值。Spring Boot也提供了一个`HttpMessageConverters`类型的便利bean（如果你使用MVC默认配置，那它就总是可用的），它提供了一些有用的方法来获取默认和用户增强的消息转换器（message converters）。具体详情可参考[76.4 自定义@ResponseBody渲染](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#howto-customize-the-responsebody-rendering)及[WebMvcAutoConfiguration](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java)源码。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jack80342.gitbook.io/spring-boot/ix.-how-to-guides/76.-spring-mvc/76.3-customize-the-jackson-objectmapper.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
