# 27.1.3. 自定义JSON序列化器和反序列化器

如果使用Jackson序列化，反序列化JSON数据，你可能想编写自己的`JsonSerializer`和`JsonDeserializer`类。自定义序列化器（serializers）通常[通过Module注册到Jackson](http://wiki.fasterxml.com/JacksonHowToCustomDeserializers)，但Spring Boot提供了`@JsonComponent`注解这一替代方式，它能轻松的将序列化器注册为Spring Beans。

你可以在`JsonSerializer`或者`JsonDeserializer`的实现上，直接使用`@JsonComponent`注解。你也可以在以内部类的形式包含序列化器/反序列化器的类上使用它，如下所示：

```
import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import org.springframework.boot.jackson.*;

@JsonComponent
public class Example {

    public static class Serializer extends JsonSerializer<SomeObject> {
        // ...
    }

    public static class Deserializer extends JsonDeserializer<SomeObject> {
        // ...
    }

}
```

`ApplicationContext`里所有的`@JsonComponent` bean会自动注册到Jackson。因为`@JsonComponent`用`@Component`进行元注解，会应用通常的组件扫描规则。

Spring Boot也提供了[`JsonObjectSerializer`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectSerializer.java)和[`JsonObjectDeserializer`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java)基础类。它们为标准的Jackson版本提供了替代选择。详情请查看[`JsonObjectSerializer`](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/jackson/JsonObjectSerializer.html)和[`JsonObjectDeserializer`](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/api/org/springframework/boot/jackson/JsonObjectDeserializer.html)的Javadoc。


---

# 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/iv.-spring-boot-features/27.-developing-web-applications/27.1.-the-spring-web-mvc-framework/27.1.3.-custom-json-serializers-and-deserializers.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.
