本章目标
使用fastjson统一处理视图返回
WebMvcConfigurerAdapter类和WebMvcConfigurer接口
使用fastjson统一处理视图返回
fastjson其实就不要说了, 大名鼎鼎的阿里产品
我们平时都是直接用
JSON.toJSON(resultUtil)
或者
ResultUtil<SysThreeCodeDtoResponse> sysThreeCodeDtoResponse = JSON.parseObject(countryRet, new TypeReference<ResultUtil<SysThreeCodeDtoResponse>>() {
});
这样的代码写多了说实话, 真的很烦, 随便一写一大堆, 那么有没有一种统一的方式来处理这种问题呢, 答案是肯定的, springboot有几个这样得类,WebMvcConfigurerAdapter和WebMvcConfigurer, 顾名思义这个都是webmvc配置的类, 这两类里面包含很各种信息,比如CORS,拦截器等等,总之配置的事都可以从这个类中处理, WebMvcConfigurerAdapter继承自WebMvcConfigurer, 其源代码是这样的:
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {}
在1.x系列的时候都是直接用WebMvcConfigurerAdapter, 但是这个类在2.x系列中已经过期了, 由WebMvcConfigurer 直接代替
@Configuration
public class FastJsonConfiguration implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty
);
List<MediaType> fastMediaType = new ArrayList<>();
fastMediaType.add(MediaType.APPLICATION_JSON_UTF8);
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaType);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastJsonHttpMessageConverter);
}
}
新建一个实体类User
![](https://img.haomeiwen.com/i3055930/31e22dadf9957926.png)
public class User {
private String name;
private int age;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
新建一个UserController
@RequestMapping(value = "/user")
@RestController
public class UserController {
@RequestMapping(value = "/getUser", method = RequestMethod.GET)
public User getUser() {
User user = new User();
user.setName("paul");
user.setAge(12);
user.setAddress("中国");
return user;
}
}
在浏览器中输入http://127.0.0.1:8083/user/getUser
![](https://img.haomeiwen.com/i3055930/0b6b5ef37109af38.png)
现在的好处是不需要在写什么Json.xxxx来处理了, 可以直接改返回什么就返回什么.....
网友评论