SpringMVC @RequestBody 處理ajax請求

來源:互聯網
上載者:User

1.問題描述

最近在和前台調試代碼時發現了如下的問題:

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unexpected character ('c' (code 99)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')。

前台是發的ajax請求,資料是一個json對象。

後台發現這個錯一般是傳遞的json資料格式有問題。

2.將對象傳到Java端

在SpringMVC環境中, @RequestBody接收的是一個Json對象的字串,而不是一個Json對象。然而在ajax請求往往傳的都是Json對象,後來發現用JSON.stringify(data)的方式就能將對象變成字串。同時ajax請求的時候也要指定dataType: "json",contentType:"application/json"這樣就可以輕易的將一個對象傳到Java端,使用@RequestBody即可綁定對象

3.如何將List對象傳到Java端:

<script type="text/javascript">      $(document).ready(function(){          var saveDataAry=[];          var data1={"userName":"test","address":"gz"};          var data2={"userName":"ququ","address":"gr"};          saveDataAry.push(data1);          saveDataAry.push(data2);                 $.ajax({             type:"POST",             url:"user/saveUser",             dataType:"json",                  contentType:"application/json",                           data:JSON.stringify(saveData),             success:function(data){                                                    }          });     });  </script> 

JSON.stringify() : 將對象轉換成json字串。

JSON.parse(): 將json字串轉換成json對象。

Java:

@RequestMapping(value = "saveUser", method = {RequestMethod.POST }})     @ResponseBody      public void saveUser(@RequestBody List<User> users) {          userService.batchSave(users);     } 

這樣是不可以的。因為spring MVC不會自動轉換為List<User>對象。傳到後台後,List中是LinkedHashMap類型。

但是使用數組就可以接受了User[] ,如下:

@RequestMapping(value = "saveUser", method = {RequestMethod.POST }})     @ResponseBody      public void saveUser(@RequestBody User[] users) {          userService.batchSave(users);     } 




相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.