2013-10-10 61 views
1

內容類型JSON的我具有類似於此假設在Spring MVC控制器

@RequestMapping(method = RequestMethod.POST) 
public void (@RequestBody SomeObject obj) { 
    // Do something 
} 

彈簧配置文件一個Spring 3.1控制器的方法是適當地設置以接受JSON。如果我發送一個內容類型設置爲「application/json」的請求並以JSON的形式發送正確的內容,那麼所有內容都按照它的設想運行。

如果我沒有指定內容類型爲「application/json」,則返回一個HTTP 415,這也是基於配置的預期結果。無論如何告訴Spring無論內容類型如何總是將RequestBody看作是JSON?

+0

不要這樣。從文檔:MappingJackson2HttpMessageConverter(或MappingJacksonHttpMessageConverter與Jackson 1.x) HttpMessageConverter實現,可以使用Jackson的ObjectMapper讀取和寫入JSON。通過使用Jackson提供的註釋,可以根據需要定製JSON映射。當需要進一步控制時,可以通過ObjectMapper屬性注入自定義ObjectMapper,以用於需要爲特定類型提供自定義JSON序列化器/反序列化器的情況。默認情況下,該轉換器支持(application/json)。 –

回答

1

要處理@RequestBody註釋參數並注入參數,Spring使用RequestResponseBodyMethodProcessor。這個HandlerMethodArgumentResolver做的第一件事是檢查Content-Type標題。如果缺少,則默認爲application/octet-stream。然後它會獲取已註冊的HttpMessageConverter實例的列表。默認情況下,這些都是

StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(); 
stringConverter.setWriteAcceptCharset(false); 

messageConverters.add(new ByteArrayHttpMessageConverter()); // if your argument is a byte[] 
messageConverters.add(stringConverter); // if your argument is a String 
messageConverters.add(new ResourceHttpMessageConverter()); // if your argument is a Resource 
messageConverters.add(new SourceHttpMessageConverter<Source>()); // if your argument is one of the javax.xml Source classes 
messageConverters.add(new AllEncompassingFormHttpMessageConverter()); // for application/x-www-form-urlencoded content-type 
if (romePresent) { 
    messageConverters.add(new AtomFeedHttpMessageConverter()); // for application/atom+xml content-type 
    messageConverters.add(new RssChannelHttpMessageConverter()); // for application/rss+xml content-type 
} 
if (jaxb2Present) { 
    messageConverters.add(new Jaxb2RootElementHttpMessageConverter()); // if your argument class is annotated with @XmlRootElement or @XmlType 
} 
if (jackson2Present) { 
    messageConverters.add(new MappingJackson2HttpMessageConverter()); // for content-type application/json and application/*+json (wildcard json) 
} 
else if (jacksonPresent) { 
    messageConverters.add(new MappingJacksonHttpMessageConverter()); // in case, but rarely, same as above 
} 

RequestResponseBodyMethodProcessor然後遍歷這個列表,爲了,並呼籲各HttpMessageConvertercanRead()。如果它返回true,則RequestResponseBodyMethodProcessor使用該HttpMessageConverter來創建參數。如果它從未找到一個,則會拋出一個HttpMediaTypeNotSupportedException,這使DispatcherServlet發送一個415響應。

有了上面的默認值,這是不可能的。你將不得不創建並註冊你自己的HttpMessageConverter可以做到這一點。請注意,它將應用於所有使用@RequestBody註釋參數的處理程序方法。


作爲一個建議,Content-Type頭是專門用於這種情況下,你應該使用它。

+0

我能夠建議我們向客戶徵求他們正確設置Content-Type標頭的要求。 – wxkevin