在SpringMVC中,可以使用@RequestBody和@ResponseBody两个注解,分别完成请求报文到对象和对象到响应报文的转换,底层这种灵活的消息转换机制就是利用HttpMessageConverter来实现的,Spring内置了很多HttpMessageConverter,比如MappingJackson2HttpMessageConverter,StringHttpMessageConverter等,下面我们来自定义自己的消息转换器来满足自己特定的需求,有两种方式:1、使用spring或者第三方提供的现成的HttpMessageConverter,2、自己重写一个HttpMessageConverter。
配置使用FastJson插件返回json数据
在springboot项目里当我们在控制器类上加上@RestController注解或者其内的方法上加入@ResponseBody注解后,默认会使用jackson插件来返回json数据,下面我们利用fastjson为我们提供的FastJsonHttpMessageConverter来返回json数据。
首先要引入fastjson的依赖:
com.alibaba
fastjson
1.2.31
接下来通过实现WebMvcConfigurer接口来配置FastJsonHttpMessageConverter,springboot2.0版本以后推荐使用这种方式来进行web配置,这样不会覆盖掉springboot的一些默认配置。配置类如下:
packagecom.example.demo;importjava.util.List;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.http.converter.HttpMessageConverter;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;importcom.alibaba.fastjson.serializer.SerializerFeature;importcom.alibaba.fastjson.support.config.FastJsonConfig;importcom.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
@Configurationpublic class MyWebmvcConfiguration implementsWebMvcConfigurer{
@Overridepublic void extendMessageConverters(List>converters) {
FastJsonHttpMessageConverter fjc= newFastJsonHttpMessageConverter();
FastJsonConfig fj= newFastJsonCon