Spring Boot默认使用Jackson来序列化和反序列化REST API中的请求和响应对象。
如果你想使用GSON而不是Jackson,那么只Gson
需要在pom.xml
文件中添加依赖项并在文件中指定一个属性application.properties
来告诉Spring Boot使用它Gson
作为首选的json映射器。
强制Spring Boot使用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
像这样直接在弹簧组件中自动装配-
@Autowire
private Gson gson;
如果您对Spring Boot如何做到这一点感到好奇,那么请看看这个GsonAutoConfiguration
类。注意它在类路径上可用@ConditionalOnClass(Gson.class)
时如何使用注释来触发自动配置Gson
。
杰克逊也以类似的方式配置了JacksonAutoConfiguration
类。
2.将首选json映射器设置为gson
现在,您可以Gson
通过在application.properties
文件中指定以下属性,将Spring Boot 用作首选的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
,您可以Gson
通过在application.properties
文件中指定各种属性来进行配置。以下属性取自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=
所有上述属性都绑定到GsonProperties
Spring Boot中定义的类。本GsonAutoConfiguration
类使用这些属性来配置GSON。
完全排除杰克逊
如果你想完全摆脱杰克逊,那么你可以将它从文件中的spring-boot-starter-web
依赖性中排除,pom.xml
如此 -
<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>
原文:https://www.callicoder.com/configuring-spring-boot-to-use-gson-instead-of-jackson/
网友评论