Spring Boot配置FastJsonHttpMessageConverter報錯'Content-Type' cannot contain wildcard type '*'
背景:
業務需求中屬性名稱和接口的名稱不匹配,項目中用fastjosn的@JSONFiled注解自定義返回json屬性名稱。
所有修改了SpringMVC的默認jackjson的httpMessage解析器。
導致原來業務采用content-type為application/octet-stream
的業務報錯。廢話少說,看代碼。
原因:
在FastJsonHttpMessageConverter
的構造器中在不指定conent-type類型的情況下支持所有類型
這個MediaType ALL
代表支持所有的content-type類型
public static final MediaType ALL = new MediaType("*", "*");
但Fastjson只是支持content-type只是支持application/json
類型的解析。
在SpringMVC在解析請求頭的時候會遍歷所有的convert看那個支持就用哪個
FastJsonHttpMessageConvert
在列表的前面,優先使用它來解析數據。
我們繼續看怎么解析的。
我們可以看到FastJsonHttpMessageConvert
的抽象類中,都會判斷該convert是否支持解析,細節可以自己去看
引文前面默認添加所有導致這里返回是true的。
然后在后面改寫請求頭的content-type為application/octet-stream
,改成,后續在框架中判斷請求頭不能為 *
這里就會報錯。
后續版本好像有改進,大家可以去探究一下。
改寫springboot自定義框架,還是自己定義一下支持的類型,以免影響其他數據類型的解析。
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
//自定義配置...
FastJsonConfig config = new FastJsonConfig();
converter.setFastJsonConfig(config);
converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON));
converters.add(0, converter);
}