在spring boot中,如果在controller中加入了@ResponseBody,就会使用相应的httpmessageconverter来进行响应内容的处理,boot中默认使用jackson来响应数据的,公司项目中大多使用的是温少温高铁的fastjson,所以考虑如何来使用fastjson。
在boot中如果使用默认的jackson来解析数据,返回一个VO对象,就会出现一个问题,假如我要返回的是个user对象,如下:
public class User {
private Long id;
private String name;
private Boolean sex;
private Date created;
public Long getId() {
return id;
}
public User setId(Long id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public User setName(String name) {
this.name = name;
return this;
}
public Boolean getSex() {
return sex;
}
public User setSex(Boolean sex) {
this.sex = sex;
return this;
}
public Date getCreated() {
return created;
}
public User setCreated(Date created) {
this.created = created;
return this;
}
}
controller如下
@GetMapping("/user")
@ResponseBody
public Object user(String api_name) {
User user = new User().setId(111111L).setSex(false).setCreated(new Date());
return user;
}
{
id: 111111,
name: null,
sex: false,
created: 1505985922932
}
name,会塞入null值
下面来讲讲换fastjson
首先,加入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
然后在启动类中,注入bean
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}
这样,重新启动就会发现,name字段没有返回了,说明换成功了。
{
created: 1506049561787,
id: 111111,
sex: false
}
总结,其实实现换fastjson的配置方式有很多,可以参考其他的文章,但是我选择这种方式来配置,是为了代码清晰,后面维护方便。
上面,我们已经使用了fastjson来替代jackson json来解析json数据,所以可以在项目中去掉jackson依赖。
boot中默认jackson依赖,是通过spring-boot-starter-web来传递性依赖jacson的
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
</exclusions>
</dependency>
exclusion出去jackson的依赖即可