方案一:启动类继承WebMvcConfigurerAdapter,覆盖方法configureMessageConverters
... @SpringBootApplication public class UserApplication extends WebMvcConfigurerAdapter{ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); // 初始化转换器 FastJsonHttpMessageConverter fastConvert = new FastJsonHttpMessageConverter(); // 初始化一个转换器配置 FastJsonConfig fastJsonConfig = new FastJsonConfig(); //用于美化格式,可注释掉 fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); // 将配置设置给转换器并添加到HttpMessageConverter转换器列表中 fastConvert.setFastJsonConfig(fastJsonConfig); converters.add(fastConvert); } public static void main(String[] args) { SpringApplication.run(UserApplication.class, args); } }
方案二:在启动类中注入 HttpMessageConverters
... @SpringBootApplication public class UserApplication { /** * 配置FastJson为Spring Boot默认JSON解析框架 * @return HttpMessageConverters */ @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { // 1.定义一个converters转换消息的对象 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); // 2.添加fastjson的配置信息,比如: 是否需要格式化返回的json数据 FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); // 3.在converter中添加配置信息 fastConverter.setFastJsonConfig(fastJsonConfig); // 4.将converter赋值给HttpMessageConverter HttpMessageConverter<?> converter = fastConverter; // 5.返回HttpMessageConverters对象 return new HttpMessageConverters(converter); } public static void main(String[] args) { SpringApplication.run(UserApplication.class, args); } }
mark一下
原文地址:https://www.cnblogs.com/wujh88/p/10333785.html
时间: 2024-10-12 03:44:24