最近工做中开发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报文时,须要注意几点:接口