####問題描述java
####解決中文亂碼的配置web
@Configuration @EnableWebMvc @ComponentScan public class MvcConfiguration extends WebMvcConfigurerAdapter { @Bean public HttpMessageConverter<String> responseBodyConverter(){ StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8")); return converter; } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); //解決中文亂碼 converters.add(responseBodyConverter()); //解決 添加解決中文亂碼後 上述配置以後,返回json數據直接報錯 500:no convertter for return value of type converters.add(messageConverter()); } }
####除了上述配置以後還有添加MappingJackson2HttpMessageConverterspring
@Bean public MappingJackson2HttpMessageConverter messageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setObjectMapper(getObjectMapper()); return converter; }
注意:responseBodyConverter和MappingJackson2HttpMessageConverter若是分開配置要確保前者不被覆蓋,否則就會出現返回springboot返回json正常,可是返回中文亂碼,或者返回中文不亂嗎,可是返回對象或者json異常。json
####解決springboot範湖中文亂碼和返回json 500錯誤的完整代碼瀏覽器
/** * spring boot 解決後臺返回 json 到前臺出現中文亂碼的問題 * 在線助手博客 http://www.it399.com/blog/index.jsp */ @Configuration @EnableWebMvc @ComponentScan public class MvcConfiguration extends WebMvcConfigurerAdapter { @Bean public HttpMessageConverter<String> responseBodyConverter(){ StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8")); return converter; } @Bean public ObjectMapper getObjectMapper() { return new ObjectMapper(); } @Bean public MappingJackson2HttpMessageConverter messageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setObjectMapper(getObjectMapper()); return converter; } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); //解決中文亂碼 converters.add(responseBodyConverter()); //解決 添加解決中文亂碼後 上述配置以後,返回json數據直接報錯 500:no convertter for return value of type converters.add(messageConverter()); } }
本文同步發佈在 在線助手-在線生成製做工具箱博客 ,轉載請註明來自 在線助手-在線生成製做工具箱博客頻道 【spring boot 解決後臺返回 json 到前臺中文亂碼以後出現返回json數據報錯 500】,原文連接:http://www.it399.com/blog/web/201805081017springboot