spring整合Gson
如何操作
配置上没啥好说的,首先去除spring自带的Jackson
# pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</exclusion>
</exclusions>
</dependency>
// application.java
@SpringBootApplication(exclude = {
JacksonAutoConfiguration.class})
public class NekoApplication {
...
引入Gson
# pom.xml
<!-- Gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
最后在application.properties中自定义Gson的属性就完成了,具体有哪些属性可以查看参考1链接,如果对参考1中属性描述有疑问,可以在参考2中搜索
#Preferred JSON mapper to use for HTTP message conversion.
spring.mvc.converters.preferred-json-mapper=gson
# Format to use when serializing Date objects.
spring.gson.date-format="YYYY-MM-DD"
# Whether to disable the escaping of HTML characters such as '<', '>', etc.
spring.gson.disable-html-escaping=false
# Naming policy :someFieldName —> SomeFieldName
spring.gson.field-naming-policy=upper_camel_case
# Whether to serialize null fields.
spring.gson.serialize-nulls=false
# Whether to enable serialization of complex map keys
spring.gson.enable-complex-map-key-serialization=true
# Whether to exclude inner classes during serialization.
spring.gson.disable-inner-class-serialization=true
然后进入正题,也就是这次在整合Gson中遇到的问题:
为什么spring.gson.exclude-fields-without-expose-annotation不起作用???
课代表: 无论true和false,只有加了@Expose
注解的字段才会序列化。要想把没有该注解的字段也加入序列化,建议直接把这个属性从propertirs或者yaml文件中删了。
在这之前,我们需要先了解
spring反序列化过程
从 message converter开始,贴一个全路径名org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver#readWithMessageConverters(org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type)
在该方法中,会获取所有注册在容器中的message converter进行遍历,查找可以进行反序列的converter
// 获取所有message converter
Iterator var11 = this.messageConverters.iterator();
HttpMessageConverter converter;
Class converterType;
GenericHttpMessageConverter genericConverter;
while(true) {
if (!var11.hasNext()) {
break label98;
}
converter = (HttpMessageConverter)var11.next();
converterType = converter.getClass()