前端頁面用ajax請求訪問后台方法 比如傳的data數據是例如data數據類型是{userGroupId:"10000",alarmItems:[{id:"1000",type:"1"},{id:"10001",type:"2"}]}, 用json解析
一般js文件寫法是date:{} 但是由於這個寫法有 {alaremItems:[]}數組 所以js寫法一般為data:JSON.stringify(jsondata), 這個jsondata是申明的數組
var jsondata={userGroupId:"10000",alarmItems:[{id:"1000",type:"1"},{id:"10001",type:"2"}]}; 然后在ajax 請求中的 data:JSON.stringify(jsondata),就可以了這個是前端傳輸
具體的如下: var jsondata={userGroupId:"10000",alarmItems:[{id:"1000",type:"1"},{id:"10001",type:"2"}]};
$.ajax({
type:"post",
contentType:"application/json;charset=utf-8",
url:"http://具體的項目到具體的方法",
data:JSON.stringify(jsondata),
async:true,
dataType:"json",
success:function(data){
console.log(data);
}
error:function(err){
}
});
后端解析json 首先第一步接受 data數據一般在controller中的方法中這樣寫 @RequestBody LinkedHashMap<String,Object> list用這個接受{userGroupId:"10000",alarmItems:[{id:"1000",type:"1"},{id:"10001",type:"2"}]};前端傳過來的 data,LinkedHashMap<String,Object> 對象
@ResponseBody
@RequestMapping(value="save")
pulbic AjaxJson save(@RequestBody LinkedHashMap<String,Object> list){
AjaxJson j=new AjaxJson();
String jsonStr=JSON.toJSONString(list);//-json字符串
JSONObject json=JSON.parseObject(jsonStr);//json對象
String uid=json.getString("userGroupId");//----獲取對應的值
JSONArray alarmItems=json.getJSONArray("alarmItems");//---獲取數組值 JSONArray是json數組 []中括號的內容
for(int i=0;i<alarmItems.size();i++){
JSONObject alarmItem=alarmItems.getJSONObject(i); //----JSONObject這個是 json的對象就是[]中的{}內容
String idstr=alarmItem.getString("id");//---獲取ID的值
String type=alarmItem.getString("type");//---獲取type的值
//---后面的就是對數據的處理 增刪改查 方法
}
j.setMsg("用戶操作成功");
return j;
}
下面講解一下AjaxJson這個類的作用和寫法
具體代碼如下:
public class AjaxJson(){
private boolean success=true;//--是否成功
private String errorCode="-1";//--錯誤代碼
private String msg="操作成功";//--- 提示信息
private LinkendHashMap<String,Object> body=new LinkedHashMap();//---封裝JSON的map
//----省略 set和get的方法生成;
//-- 其中又寫了兩個其他的方法 如下:
public void put(String key,Object value){
body.put(key,value);
}
public void remove(String key){
body.remove(key);
}
@JsonIgnore//--返回對象時忽略此屬性 JsonMapper類繼承了 ObjectMapper這個類
public String getJsonStr(){
String json=JsonMapper.getInstance().toJson(this);
return json;
}
}