HttpMediaTypeNotSupportedException: Content type 'application/json;' not supported 問題原因之一
阿新 • • 發佈:2018-12-24
方法配置:
@RequestMapping(value = "/check" ,method = RequestMethod.POST)
@ResponseBody
public Object check(@RequestBody A a)
錯誤:
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported
網上看到有很多情況會導致這個問題,這裡我說一下我這裡的問題原因。
看Spring的原始碼:
protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter methodParam, Class<T> paramType) throws IOException, HttpMediaTypeNotSupportedException { MediaType contentType = inputMessage.getHeaders().getContentType(); if (contentType == null) { contentType = MediaType.APPLICATION_OCTET_STREAM; } for(HttpMessageConverter<?> messageConverter : this.messageConverters) { if (messageConverter.canRead(paramType, contentType)) { if (logger.isDebugEnabled()) { logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType + "\" using [" + messageConverter + "]"); } return ((HttpMessageConverter<T>) messageConverter).read(paramType, inputMessage); } } throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes); } public boolean canRead(Class<?> clazz, MediaType mediaType) { return supports(clazz) && canRead(mediaType); }
經分析應該是canRead返回了false, 記得之前碰到一個問題是bean裡面屬性的get,set方法不規範導致json轉換報錯,後面檢查程式碼發現,這次是同樣的問題,在A裡面引用了B類,B裡面有一個屬性c,有兩個setC方法,引數不一樣,是過載的方法,這個方法過載導致json轉換不支援,然後canRead方法了false.
同樣,如果你的bean裡面有get或set方法,但是沒有這個屬性,比如你有一個getName方法,但是bean裡面沒有name這個屬性,在轉換json時也會報錯。