spring boot 解決後臺返回 json 到前臺中文亂碼以後出現返回json數據報錯 500:no convertter for return value of type

####問題描述java

  • spring Boot 中文返回給瀏覽器亂碼 解析成問號?? fastJson jackJson
  • spring boot 新增配置解決後臺返回 json 到前臺中文亂碼以後,出現返回json數據報錯:no convertter for return value of type
  • 註釋掉解決中文亂碼的問題以後返回對象json正常
  • Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class www.it399.com.controller.file.ResultBean

####解決中文亂碼的配置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());
    }

}

原文連接 http://www.it399.com/blog/web/201805081017springboot

相關文章
相關標籤/搜索