最近工做中開發RESTful接口須要處理客戶端上傳的json,圖方便想起Spring的Controller中有@RequestBody能夠優雅地完成json報文與Java類的映射,可是使用時碰到了 「The request sent by the client was syntactically incorrect.」 異常,記得之前也有碰到過,可是沒有把緣由記錄下來,此次又掉坑裏了。又baidugoogle了一會才解決,好記性不如爛筆頭,此次仍是好好檢討下。java
###異常緣由 字面上理解就是「客戶端發送的請求語法不正確」這種意義不明的異常信息。語法不正確說的是什麼語法?其實這裏指的是上傳的json報文不符合跟對應Java類的映射關係。舉個栗子: 好比頁面上Ajax請求的json報文以下:json
{"id":1,"name":"zhangsan","gender":1}
Java工程中對應的類定義:app
public class Person(){ private Integer id; //...setter and getter } //Spring中Congroller代碼 @Controller @RequestMapping(value = "/test") public class TestController{ @RequestMapping(value = "/index") public String index(@RequestBody Person p){ //do something return "testpage"; } }
用上述代碼映射客戶端上傳的json報文就會報「The request sent by the client was syntactically incorrect.」異常。緣由很簡單,由於上傳的json報文中有id,name,gender三個字段,而用來映射的java類中只有id字段,匹配不了,這就是所謂的「語法不正確」。若是將上述 Person 類的定義改爲:google
public class Person(){ private Integer id; private String name; private Integer gender; //...setter and getter }
程序再跑起來沒問題了。並且,這裏的Person還能夠多定義幾個字段,即:只要客戶度上傳的json報文字段都有定義,且類型定義正確,使用@RequestBody映射時就不會報「The request sent by the client was syntactically incorrect.」異常。code
###總結 在Spring的Controller中使用@RequestBody映射客戶端請求的json報文時,須要注意幾點:接口