spring boot 使用fastjson 处理json数据中文乱码 默认使用 ISO-8859-1编码格式

时间:2025-04-01 18:17:41
package com.peng; import java.util.ArrayList; import java.util.List; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; /*@SpringBootApplication public class SpringBootFastjsonDemo20170614Application { @Bean public HttpMessageConverters fastJsonHttpMessageConverters(){ FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); (); (fastJsonConfig); HttpMessageConverter<?> converter = fastJsonHttpMessageConverter; return new HttpMessageConverters(converter); } public static void main(String[] args) { (, args); } }*/ @SpringBootApplication public class SpringBootFastjsonDemo20170614Application extends WebMvcConfigurerAdapter{ /** * 利用fastjson替换掉jackson,且解决中文乱码问题 */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); converters.add(fastJsonHttpMessageConverter); } public static void main(String[] args) { SpringApplication.run(SpringBootFastjsonDemo20170614Application.class, args); } }