1.Json傳遞數據兩種方式(json大全)
----------------------------字符串
var list1 = ["number","name"]; var param = {}; param["list1"] = list1; param["test"] ="java"; var json = JSON.stringify(param); $.ajax({ type: 'POST', url: CTX + '雙擊查看原圖eckInvoice雙擊查看原圖st', data: { ids: json }, dataType: "json", async:false, success: function(data){ if(data.success) { value = 'success'; $("#table").bootstrapTable('refresh'); } else { value = 'fail'; } showAlertFrame(value, data.message); }, error: function (e) { } }); };
@PostMapping(value = "/list") @ResponseBody public void invoiceDetail2(String ids) { JSONObject jsonobject = JSONObject.parseObject(ids); JSONArray jsonArray = JSONArray.parseArray(jsonobject.get("list1").toString()); List<String> list = jsonArray.toJavaList(String.class); } @PostMapping(value = "/list2") @ResponseBody public void list2(@RequestBody ScannerVo vo) { List<String> list = vo.getList1(); // JSONArray jsonArray = JSONArray.parseArray(vo.getList1()); // List<String> list = jsonArray.toJavaList(String.class); }
-------------------------------------對象
public class ScannerVo {
private List list1;
public List getList1() {
return list1;
}
public void setList1(List list1) {
this.list1 = list1;
}
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
private String test;
}
var getInvoice = function (invoiceCode,invoiceNum) {
var list1 = ["number","name"];
var param = {};
param["list1"] = list1;
param["test"] ="java";
var json = JSON.stringify(param);
$.ajax({
type: 'POST',
url: CTX + '/checkInvoice/list2',
data: json,
dataType: "json",
async:false,
contentType: 'application/json',
success: function(data){
if(data.success) {
value = 'success';
$("#table").bootstrapTable('refresh');
} else {
value = 'fail';
}
showAlertFrame(value, data.message);
},
error: function (e) {
}
});
};
@PostMapping(value = "雙擊查看原圖st2") @ResponseBody public void list2(@RequestBody ScannerVo vo) { List<String> list = vo.getList1(); // JSONArray jsonArray = JSONArray.parseArray(vo.getList1()); // List<String> list = jsonArray.toJavaList(String.class); }
springmvc接收json數據的4種方式
ajax我經常用到,傳的數據是json數據,json數據又有對象,數組。所有總結下springmvc獲取前端傳來的json數據方式:
1、以RequestParam接收
前端傳來的是json數據不多時:[id:id],可以直接用@RequestParam來獲取值
@Autowired private AccomodationService accomodationService; @RequestMapping(value = "/update") @ResponseBody public String updateAttr(@RequestParam ("id") int id) { int res=accomodationService.deleteData(id); return "success"; }
2、以實體類方式接收
前端傳來的是一個json對象時:{【id,name】},可以用實體類直接進行自動綁定
@Autowired private AccomodationService accomodationService; @RequestMapping(value = "/add") @ResponseBody public String addObj(@RequestBody Accomodation accomodation) { this.accomodationService.insert(accomodation); return "success"; } !
3、以Map接收
前端傳來的是一個json對象時:{【id,name】},可以用Map來獲取
@Autowired private AccomodationService accomodationService; @RequestMapping(value = "/update") @ResponseBody public String updateAttr(@RequestBody Map<String, String> map) { if(map.containsKey("id"){ Integer id = Integer.parseInt(map.get("id")); } if(map.containsKey("name"){ String objname = map.get("name").toString(); } // 操作 ... return "success"; }
4、以List接收
當前端傳來這樣一個json數組:[{id,name},{id,name},{id,name},...]時,用List<E>接收
@Autowired private AccomodationService accomodationService; @RequestMapping(value = "/update") @ResponseBody public String updateAttr(@RequestBody List<Accomodation> list) { for(Accomodation accomodation:list){ System.out.println(accomodation.toString()); } return "success"; }
Springmvc接受json參數總結
關於springmvc的參數我覺得是個頭痛的問題,特別是在測試的時候,必須要正確的注解和正確的contype-type 后端才能被正確的請求到,否則可能報出400,415等等bad request。
1,最簡單的GET方法,參數在url里面,比如:
@RequestMapping(value = “/artists/{artistId}”, method = {RequestMethod.GET})
@PathVariable去得到url中的參數。
public Artist getArtistById(@PathVariable String artistId)
2,GET方法,參數接在url后面。
@RequestMapping(value = "/artists", method = {RequestMethod.GET}) public ResponseVO getAllArtistName( @RequestParam(name = "tagId", required = false) final String tagId)
訪問的時候/artists?tagId=1
@RequestParam相當於request.getParameter(“”)
3,POST方法,后端想得到一個自動注入的對象
@RequestMapping(value = "/addUser", method = {RequestMethod.POST}) public void addUser(@RequestBody UserPO users){


---------------------

---------------------
如果前端使用的$.ajax來發請求,希望注入一個bean。這時又有坑了,代碼如下:
$.ajax({ headers: { Accept: "application/json; charset=utf-8" }, method : 'POST', url: "http://localhost:8081/user/saveUser", contentType: 'application/json', dataType:"json", data: json, //async: false, //true:異步,false:同步 //contentType: false, //processData: false, success: function (data) { if(data.code == "000000"){ alert(data.desc); window.location.href="http://localhost:8081/login.html"; } }, error: function (err) { alert("error"); }}); ---------------------
馬上就報錯了:
**error
:
“Bad Request”
exception
:
“org.springframework.http.converter.HttpMessageNotReadableException”
message
:
“JSON parse error: Unrecognized token ‘name’: was expecting ‘null’, ‘true’, ‘false’ or NaN; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token ‘name’: was expecting ‘null’, ‘true’, ‘false’ or NaN↵ at [Source: java.io.PushbackInputStream@7fc056ba; line: 1, column: 6]”
path
:
“/user/saveUser”
status
:
400
timestamp
:
1518094430114**
這是看看發送的參數:

居然不是我拼裝好的json,
data: json, 改成 data: JSON.stringify(json),后端接收json String,json只是個對象,所以解析不了!
---------------------
4,POST方法,需要得到一個List的類型
@RequestMapping(value = “/addUser”, method = {RequestMethod.POST})
public void addUser(@RequestBody List users){
---------------------

5,POST方法,后台需要得到一個List類型。
@RequestMapping(value = "/getPlayURL", method = {RequestMethod.POST}) @ResponseBody public List<Song> getPlayUrlBySongIds( @RequestParam(name = "songId",required = false) List<String> songIdList) { ---------------------
004-SpringMVC-如何接收各種參數(普通參數,對象,JSON, URL)
在交互的過程中,其中一個關鍵的節點就是獲取到客戶端發送過來的請求參數,本篇文章,我們來羅列下SpringMVC對於各種數據的獲取方式:說明:以下重點在講解如何獲取參數上,所以返回的數據不是重點1,普通方式,請求參數名跟Controller的方法參數一致1.1 創建Controller
--------------------- 
1.2 發送請求做測試(由於方法沒有限制請求方式,所以get和post均可)

2,當請求參數過多時,以對象的方式傳遞
2.1 創建一個類,包含多個參數(簡單不附帶圖了)
2.2 前台傳遞參數的方式不變

2.3 后台接收參數的方法


原因很簡單,是因為SpringMVC默認是沒有對象轉換成json的轉換器,所以需要手動添加jackson依賴。<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.8.8</version></dependency>
---------------------
3,當請求參數名跟方法參數名不一致時,@RequestParam


4,當需要傳遞Json格式的數據是,@RequestBody
4.1 前台傳遞的方式是json

5,通過URL的方式傳遞參數

