需求:spring mvc接收ajax提交的JSON數據,並反序列化爲對象,代碼以下:ajax
前臺JS代碼:spring
//屬性要與帶轉化的對象屬性對應 var param={name:'語文',price:16}; $.ajax({ url: "/book/adddata", type: "POST", dataType: 'json', //必需設定,後臺@RequestBody會根據它作數據反序列化 contentType:"application/json", //必需把JSON數據以字符串的格式提交 data:JSON.stringify(param), success: function (data) { alert('添加成功'); }, error: function (XMLHttpRequest, textStatus) { alert('添加失敗'); } });
後臺JAVA代碼:json
@RequestMapping(value="adddata") @ResponseBody public Protocol addData(Model model, @RequestBody Book book) { Book reData = bookService.add(book); return reData; }