轉自: http://blog.csdn.net/tiantiandjava/article/details/46125141
項目中想用@RequestBody直接接收json串轉成對象
網上查了使用方法,看着非常簡單,不過經過測試很快發現頁面直接報415錯誤。
- <body>
- <h1>HTTP Status 415 - </h1>
- <HR size="1" noshade="noshade">
- <p>
- <b>type</b> Status report
- </p>
- <p>
- <b>message</b>
- <u></u>
- </p>
- <p>
- <b>description</b>
- <u>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.</u>
- </p>
- <HR size="1" noshade="noshade">
- <h3>Apache Tomcat/6.0.41</h3>
- </body>
經過一通查,多半的解決方法實說header里的 Content-Type 一定 application/json
但是問題依然沒有解決。
最后在《Spring in Action》里找到一個信息
有兩個前提條件:
The request’sContent-Typeheader must be set toapplication/json.
The JacksonJSONlibrary must be available on the application’s classpath.
我滿足了第一個,所以在classpath中添加了一個jar。問題解決了。
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>2.5.3</version>
- </dependency>
所以如果大家遇到了同樣的問題,可以先排除一下這兩個因素。
------------------------------
還有一種情況,在以上兩個條件都滿足的情況下,還是報同樣的錯誤。
在springmvc的配置文件中必須有:
- <!-- 默認的注解映射的支持 -->
- <mvc:annotation-driven />
如果沒有這個配置也是會報這個錯的!
為什么會引入jackson-databind包呢,因為默認的配置會用到:
- com.fasterxml.jackson.databind.ObjectMapper