一、pom配置FastJson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
配置 FastJson
@Configuration
public class JsonConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.PrettyFormat);
// 创建配置类
config.setSerializerFeatures(
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty
);
//此处是全局处理方式
config.setDateFormat("yyyy-MM-dd HH:mm:ss");
config.setCharset(StandardCharsets.UTF_8);
// 创建MediaType的集合
List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
// 设置编码格式为UTF8
supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
// 将supportedMediaTypes对象赋值给fastJsonHttpMessageConverter的SupportedMediaTypes属性
fastJsonHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
fastJsonHttpMessageConverter.setFastJsonConfig(config);
converters.add(fastJsonHttpMessageConverter);
}
}
三、创建实体类
public class BaseModel {
public BaseModel(boolean state, String msg, Object data) {
this.state = state;
this.msg = msg;
this.data = data;
}
private boolean state;
private String msg;
private Object data;
public boolean getState() {
return state;
}
public void setState(boolean state) {
this.state = state;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getObject() {
return data;
}
public void setObject(Object data) {
this.data = data;
}
}
四、Controller 中返回Json数据 usersService.selectAll() 查询数据库数据
@RestController
public class HelloController {
@Autowired
private UsersService usersService;
@RequestMapping(value = "/",method = RequestMethod.GET)
public BaseModel index(){
return new BaseModel(true,null,usersService.selectAll());
}
}