引入fastjson依赖库 :
1 2 3 4 5
| <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.31</version> </dependency>
|
官方文档说的1.2.10以后,会有两个方法支持HttpMessageconvert,一个是FastJsonHttpMessageConverter,支持4.2以下的版本,一个是FastJsonHttpMessageConverter4支持4.2以上的版本,具体有什么区别暂时没有深入研究。这里也就是说:低版本的就不支持了,所以这里最低要求就是1.2.10+。
配置fastjon(支持两种方法) :
第一种方法:
(1)启动类继承WebMvcConfigurerAdapter
(2)覆盖方法configureMessageConverters
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @SpringBootApplication public class App extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures( SerializerFeature.PrettyFormat ); fastConverter.setFastJsonConfig(fastJsonConfig); converters.add(fastConverter); } public static void main(String[] args) { SpringApplication.run(App.class) ; } }
|
第二种方法:
(1)在App.java启动类中, 注入Bean : HttpMessageConverters
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @SpringBootApplication public class App { @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); } public static void main(String[] args) { SpringApplication.run(App.class) ; } }
|
新建User.java, 使用fastjson格式化日期。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| public class User { private Integer id; private String name; private Integer age; @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date createTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }
|
新建UserController类:
1 2 3 4 5 6 7 8 9 10 11 12 13
| @RestController public class UserController { @GetMapping("getUser") public User getUser() { User user = new User() ; user.setId(1); user.setName("jason"); user.setAge(24); user.setCreateTime(new Date()); return user ; } }
|
启动App.java
访问 http://127.0.0.1:8080/getUser ,结果如下:
1 2 3 4 5 6
| { "age": 24, "createTime": "2017-08-24 21:55:05", "id": 1, "name": "jason" }
|