spring cloud中返回数据编码问题

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


@Configuration
public class CustomMVCConfiguration extends WebMvcConfigurerAdapter{

@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
}

@Override
	public void configureContentNegotiation(
			ContentNegotiationConfigurer configurer) {

	}
}

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


@Override
	public 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);
	}

	@Override
	public void configureContentNegotiation(
			ContentNegotiationConfigurer configurer) {
		configurer.favorPathExtension(false);
	}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值