1.先在项目中添加fastjson依赖:
1 2 3 4 5 | <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> |
2.1第一种方法,让入口类实现WebMvcConfigure接口,并重写configureMessageConverters方法:
1 2 3 | public class App implements WebMvcConfigurer{ ...... } |
重写方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { //第一种配置fastJson方法 FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //处理中文乱码问题 List<MediaType> fastMediaTypes = new ArrayList<MediaType>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); converters.add(fastJsonHttpMessageConverter); } |
2.2第二种方法,直接在入口类加入@Bean注解并加入方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 | @Bean public HttpMessageConverters fastJsonHttpMessage() { FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //处理中文乱码问题 List<MediaType> fastMediaTypes = new ArrayList<MediaType>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); return new HttpMessageConverters(fastJsonHttpMessageConverter); } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步