1、添加fastjson配置
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
2、重写configureMessageConverters
@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);
}
3、运行http://127.0.0.1:8080/getstudent
浏览器输出有乱码
4、修改Controller
@RequestMapping(value = "/getstudent", produces = "application/json; charset=utf-8")
public Student getStudent() {
Student student=new Student();
student.id=1;
student.name="小明";
return student;
}
5、再次运行,正常,并且可以看到fastjson已经自动格式化了输出内容
6、常用注解
@JSONField(serialize = false) //不参与格式化
@JSONField(serialzeFeatures=SerializerFeature.WriteMapNullValue) //输出NULL
7、也可以代码中直接使用
System.out.println(JSON.toJSONStringWithDateFormat(ao, "yyyy-MM-dd HH:mm:ss.SSS"));
总结:本篇其实和SpringBoot关系不大,传统SpringMVC+Hibernate也可以用。