spring cloud中返回数据编码问题

来源:互联网 发布:服务器网络架构 编辑:程序博客网 时间:2024/06/06 09:32

spring cloud集成了spring mvc,默认返回的格式都是json,utf-8。 如果在项目中发现返回的json失败,或者编码有问题,那需要检查一下是否做了以下配置:


@Configurationpublic class CustomMVCConfiguration extends WebMvcConfigurerAdapter{@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {}@Overridepublic void configureContentNegotiation(ContentNegotiationConfigurer configurer) {}}

如果需要自定义配置,需要对下面配置进行编码和数据的转换:


@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {        /*            using the StringHttpMessageConverter to handle with simple String message.        */StringHttpMessageConverter stringConverter= new StringHttpMessageConverter();stringConverter.setDefaultCharset(Charset.forName("UTF-8"));converters.add(stringConverter);        /*            using the FastJsonHttpMessageConverter to handle these below.            1. text/html;charset=UTF-8                              a page(htm/html/jsp etc.)            2. application/json;charset=utf-8                       json data type response            3. text/plain;charset=UTF-8                             a text or string etc.            4. application/x-www-form-urlencoded;charset=utf-8      standard encoding type. convert form data to a key-value.            ...        */FastJsonHttpMessageConverter4 fastJsonConverter = new FastJsonHttpMessageConverter4();FastJsonConfig fastJsonConfig = new FastJsonConfig();fastJsonConfig.setCharset(Charset.forName("UTF-8"));fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);fastJsonConverter.setFastJsonConfig(fastJsonConfig);List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();MediaType text_plain = new MediaType(MediaType.TEXT_PLAIN, Charset.forName("UTF-8"));MediaType text_html = new MediaType(MediaType.TEXT_HTML, Charset.forName("UTF-8"));MediaType x_www_form_urlencoded_utf8 = new MediaType(MediaType.APPLICATION_FORM_URLENCODED, Charset.forName("UTF-8"));supportedMediaTypes.add(text_html);supportedMediaTypes.add(text_plain);supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);supportedMediaTypes.add(x_www_form_urlencoded_utf8);fastJsonConverter.setSupportedMediaTypes(supportedMediaTypes);converters.add(fastJsonConverter);super.configureMessageConverters(converters);}@Overridepublic void configureContentNegotiation(ContentNegotiationConfigurer configurer) {configurer.favorPathExtension(false);}