1. 如何集成fastjson?
1.1 在pom.xml文件中加入:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
1.2 在启动类中加入:
package com.npf.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
/**
*
* @author Jack
*
*/
@SpringBootApplication
public class SpringBootBootstrap {
public static void main(String[] args) {
SpringApplication.run(SpringBootBootstrap.class, args);
}
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters(){
//1. 需要定义一个converter转换消息的对象
FastJsonHttpMessageConverter fasHttpMessageConverter = new FastJsonHttpMessageConverter();
//2. 添加fastjson的配置信息,比如:是否需要格式化返回的json的数据
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
//3. 在converter中添加配置信息
fasHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fasHttpMessageConverter;
return new HttpMessageConverters(converter);
}
}
1.3 在实体类中可以加入定制Json格式化
package com.npf.springboot.entity;
import com.alibaba.fastjson.annotation.JSONField;
public class User {
private int id;
private String name;
private String password;
@JSONField(format="yyyy-MM-dd: HH:mm")
private java.util.Date createTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public java.util.Date getCreateTime() {
return createTime;
}
public void setCreateTime(java.util.Date createTime) {
this.createTime = createTime;
}
}
1.4 运行测试

Github地址:https://github.com/spring-boot-learn/springboot03