Spring Boot配置Gson替代Jackson
Spring Boot 默认使用 Jackson 来序列化和反序列化 REST API 中的请求和响应对象。
如果您想使用 GSON 而不是 Jackson,那么只需在 pom.xml 文件中添加 Gson 依赖项并在 application.properties 文件中指定一个属性来告诉 Spring Boot使用 Gson 作为首选的 json 映射器。
Jackson在序列化对象时会出现非预期的结果,比如is开头的属性isAccountNonExpired会被截取为accountNonExpired
强制使用GSON 替代Jackson
1. 添加 Gson 依赖
打开您的 pom.xml 文件并像这样添加 GSON 依赖项 -
<!-- Include GSON dependency -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.4</version>
</dependency>
一旦你这样做了,Spring Boot 将检测 Gson 对类路径的依赖,并自动创建一个具有合理默认配置的 Gson bean。您也可以像这样直接在组件中自动装配 gson -
@Autowireprivate Gson gson;
如果您对 Spring Boot 如何做到这一点感到好奇,那么请查看这个GsonAutoConfiguration类。注意当 Gson 在类路径上可用时,它如何使用 @ConditionalOnClass(Gson.class) 注释来触发自动配置。
Jackson 也以类似的方式配置了JacksonAutoConfiguration类。
2. 将首选 json 映射器设置为 gson
您现在可以通过在 application.properties 文件中指定以下属性来要求 Spring Boot 使用 Gson 作为首选的 json 映射器 -
# Preferred JSON mapper to use for HTTP message conversion.
spring.http.converters.preferred-json-mapper=gson
这就是强制 Spring Boot 使用 Gson 而不是 Jackson 所需的全部操作。
在 Spring Boot 中配置 GSON
现在您的 Spring Boot 应用程序正在使用 Gson,您可以通过在 application.properties 文件中指定各种属性来配置 Gson。以下属性取自 Spring Boot Common Application Properties 索引页 -
# GSON (GsonProperties)
# Format to use when serializing Date objects.
spring.gson.date-format=
# Whether to disable the escaping of HTML characters such as '<', '>', etc.
spring.gson.disable-html-escaping=
# Whether to exclude inner classes during serialization.
spring.gson.disable-inner-class-serialization=
# Whether to enable serialization of complex map keys (i.e. non-primitives).
spring.gson.enable-complex-map-key-serialization=
# Whether to exclude all fields from consideration for serialization or deserialization that do not have the "Expose" annotation.
spring.gson.exclude-fields-without-expose-annotation=
# Naming policy that should be applied to an object's field during serialization and deserialization.
spring.gson.field-naming-policy=
# Whether to generate non executable JSON by prefixing the output with some special text.
spring.gson.generate-non-executable-json=
# Whether to be lenient about parsing JSON that doesn't conform to RFC 4627.
spring.gson.lenient=
# Serialization policy for Long and long types.
spring.gson.long-serialization-policy=
# Whether to output serialized JSON that fits in a page for pretty printing.
spring.gson.pretty-printing=
# Whether to serialize null fields.
spring.gson.serialize-nulls=
以上所有属性都绑定到 Spring Boot 中定义的名为GsonProperties的类。 GsonAutoConfiguration 类使用这些属性来配置 Gson。
比如设置时间格式化
spring.gson.date-format= "yyyy-MM-dd HH:mm:ss"
Jackson
如果你想完全摆脱Jackson,那么你可以像这样从 spring-boot-starter-web 文件中的依赖项中排除它 -
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- Exclude the default Jackson dependency -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</exclusion>
</exclusions>
</dependency>