自上一节:SpringBoot 02_返回json数据,可以返回json数据之后,由于有些人习惯于不同的Json框架,比如fastjson,这里介绍一下如何在SpringBoot中集成fastjson来实现对数据的json序列化。
在使用fastjson时,可以有以下两种集成方式,但是都需要引入fastjson的依赖包
1:引入fastjson依赖包
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.31</version> </dependency>
2:新建User.java
@Data public class User { // 姓名 private String name; // 年龄 private Integer age; // 生日private LocalDateTime birthday; // 备注private String remark; }
3:集成fastjson
1:方式一
- 启动类继承extends WebMvcConfigurerAdapter
- 覆盖方法configureMessageConverters
启动类:
@SpringBootApplication public class FastjsonApplicationOne extends WebMvcConfigurerAdapter{ /** * 在这里注册fastjson的类型转换器,需要版本1.2.10以后的 * 方式一: * 通过继承WebMvcConfigurerAdapter,然后添加converter * @param converters */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); converters.add(fastJsonHttpMessageConverter); } public static void main(String[] args) { SpringApplication.run(FastjsonApplicationOne.class, args); } }
2:方式二
- 在App.java启动类中,注入Bean : HttpMessageConverters
启动类
@SpringBootApplication public class FastjsonApplicationTwo { public static void main(String[] args) { SpringApplication.run(FastjsonApplicationTwo.class, args); } @Bean HttpMessageConverters fastJsonHttpMessageConverters(){ FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastJsonHttpMessageConverter; return new HttpMessageConverters(converter); } }
4:Controller类的编写
@RestController @RequestMapping("/fastJson") public class FastJsonController { @GetMapping("/getUser") public User getUser(){ User user = new User(); user.setName("Bob"); user.setAge(5); user.setBirthday(LocalDateTime.now()); user.setRemark("This is remark."); return user; } }
5:分别执行FastjsonApplicationOne和FastjsonApplicationTwo的主方法,输入:lcoalhost:8080/fastJson/getUser进行测试:
如果能够返回上述结果,恭喜你,你已经可以利用SpringBoot集成fastjson来对返回数据进行json化处理了。