1.2自定义转换器(不推荐)(不建议使用)

常见的JSON处理器除了 jackson-databind之外,还有 Gson 和 fastjson ,这里针对常见用法分别举例。

1 .使用Gson   

Gson是Google的一个开源JSON解析框架。使用Gson,需要先除去默认的jackson-databind,然后加入Gson依赖,代码如下:


<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
   <exclusions>
      <exclusion>
         <groupId>com.fasterxml.jackson.core</groupId>
         <artifactId>jackson-databind</artifactId>
      </exclusion>
   </exclusions>
</dependency>

<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
</dependency>


由于 Spring Boot 中默认提供了 Gson 的自动转换类 GsonHttpMessageConvertersConfiguration, 因此Gson的依赖添加成功后,可以像使用jackson-databind那样直接使用Gson。

但是在Gson进行 转换时,如果想对日期数据进行格式化,那么还需要开发者自定义 HttpMessageConverter。自定义 HttpMessageConverter 可以通过如下方式。

首先看 GsonHttpMessageConvertersConfiguration 中的一段源码:


@Bean
@ConditionalOnMissingBean
public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
	GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
	converter.setGson(gson);
	return converter;
}


@ConditionalOnMissingBean 注解表示当项目中没有提供 gsonHttpMessageConverter 时才会使用默认的 GsonHttpMessageConverter,所以开发者只需要提供一个 GsonHttpMessageConverter 即可, 代码如下:


1 (^Configuration
2 public class GsonConfig (
3 @Bean
4 GsonHttpMessageConverter gsonHttpMessageConverter() (
5 GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
6 GsonBuilder builder = new GsonBuilder();
7 builder.setDateFormat("yyyy-MM-ddH);
8 builder.excludeFieldsWithModifiers(Modifier.PROTECTED);
9 Gson gson = builder.create();
10 converter.setGson(gson);
11 return converter;
12 )
13 }

代码解释:
•开发者自己提供一个GsonHttpMessageConverter的实例。
•设置Gson解析时日期的格式。
•设置Gson解析时修饰符为protected的字段被过滤掉。
•创建Gson对象放入GsonHttpMessageConverter的实例中并返回converter。
此时,将Book类中的price字段的修饰符改为protected,代码如下:
1public class Book (
2private String name;
3private String author;
4protected Float price;
5private Date publicationDate;
6getter/setter
7}
最后,在浏览器中输入“http://localhost:8080/book”,即可看到运行结果,如图4-2所示。
1 o cal h o st:8080/boo k X
<- CO© localhost:8080/book
{"name":"三国演义”,"author":"罗贯中",*publicationDate*: w2019-07-08*}
图4-2


2.使用 fastjson   

fastjson是阿里巴巴的一个开源JSON解析框架,是目前JSON解析速度最快的开源框架,该 
框架也可以集成到Spring Boot中。不同于Gson, fastjson继承完成之后并不能立马使用,需要开 发者提供相应的HttpMessageConverter后才能使用,集成fastjson的步骤如下。
首先除去jackson-databind依赖,引入fastjson依赖:
〈dependency〉
<groupld>org.springframework.boot</groupld> <artifactld>spring-boot-starter-web</artifactld> <exclusions>
<exclusion>
<groupld>com.fasterxml.jackson.core</groupld> <artifactld>jackson-databind</artifactld> </exclusion>
</exclusions>
</dependency>
<dependency>
<groupld>com.alibaba</groupld>
<artifactld>fastjson</artifactld>
<version>l.2.47</version>
</dependency>
然后配置 fastjson 的 HttpMessageConverter:
1 @Configuration
2 public class MyFastJsonConfig (
3 @Bean
4 FastJsonHttpMessageConverter fastJsonHttpMessageConverter() (
5 FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter ();
6 FastJsonConfig config = new FastJsonConfig();
7 config. setDateFormat ("yyyy-MM-dd'*);
8 config. setCharset (Charset. forName ("UTF-8'1));
9 config.setSerializerFeatures(
10 SerializerFeature.WriteClassName,
11 SerializerFeature.WriteMapNullValue,
12 SerializerFeature.PrettyFormatz
13 SerializerFeature.WriteNullListAsEmpty,
14 SerializerFeature.WriteNullStringAsEmpty
15 );
16 converter.setFastJsonConfig(config);
17 return converter;
18
19 }
}

代码解释:
• 自定义 MyFastJsonConfig,完成对 FastJsonHttpMessageConverter Bean 的提供。
•第7~15行分别配置了 JSON解析过程的一些细节,例如日期格式、数据编码、是否在生成的 JSON中输出类名、是否输出value为null的数据、生成的JSON格式化、空集合输出[]而非 null、空字符串输出"”而非null等基本配置。
MyFastJsonConfig配置完成后,还需要配置一下响应编码,否则返回的JSON中文会乱码,在
application.properties 中添加如下配置:
| 1 | spring・http.encoding.force-response=true
接下来提供BookController进行测试。BookController和上一小节一致,运行成功后,在浏览 器中输入“http://localhost:8080/book”,即可看到运行结果,如图4・3所示。
0 O | 0 localhost:8080/book
(B@type-:"org.sang.BookB, "author*1:"罗貫中”,Fame":二 8pricew:3O.OF, BpublicationDate":n2018-07-09"}
图中3
对于FastJsonHttpMessageConverter的配置,除了上面这种方式之外,还有另一种方式。
在Spring Boot项目中,当开发者引入spring-boot-starter-web依赖之后,该依赖又依赖了 spring-boot-autoconfigure,在这个自动化配置中,有一个 WebMvcAutoConfiguration 类提供了对 Spring MVC最基本的配置,如果某一项自动化配置不满足开发需求,开发者可以针对该项自定义 配置,只需要实现 WebMvcConfigurer接口即可(在Spring 5.0之前是通过继承 WebMvcConfigurerAdapter类来实现的),代码如下:
1 ^Configuration
2 public class MyWebMvcConfig implements WebMvcConfigurer (
3 @Override
4 public void configureMessageConverters(List<HttpMessageConverter<?»
5 converters) (
6 FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter ();
7 FastJsonConfig config = new FastJsonConfig();
8 config.setDateFormat("yyyy-MM-dd");
9 config.setCharset(Charset.forName("UTF-8"));
10 config.setSerializerFeatures(
11 SerializerFeature.WriteClassName,
12 SerializerFeature.WriteMapNullValue,
13 SerializerFeature.PrettyFormat,
14 SerializerFeature.WriteNullListAsEmpty,
15 SerializerFeature.WriteNullStringAsEmpty
16 );
17 converter.setFastJsonConfig(config);
18 converters.add(converter);
19 }
}

代码解释:
•自定义 MyWebMvcConfig 类并实现 WebMvcConfigurer 接 口中的 configureMessageConverters 方法。
•将自定义的 FastJsonHttpMessageConverter 加入 converters 中。

如果使用了 Gson,也可以采用这种方式配置,但是不推荐。因为当项目中没有 GsonHttpMessageConverte 1•时,Spring Boot 自己会提供一个 GsonHttpMessageConverter,此 时重写 configureMessageConverters 方法,参数converters 中已经有 GsonHttpMessageConverter 的实例了,需要替换已有的GsonHttpMessageConverter实例,操作比较麻烦,所以对于Gson, 推荐直接提供 GsonHttpMessageConverter。