jQuery ajax 傳遞JSON數組到Spring Controller


     jQuery ajax傳遞單個JSON對象到后台很容易,這里記錄的是傳遞多個JSON對象組成的JSON數組到java 后台,並說明java如何解析JSON數組。

    1、js代碼

 var relationArrays=new Array();
  //獲取所有組的人員信息grid數據
  var allGrid= $(".userGrid");
  for(var i=0;i<allGrid.length;i++){
    var rows=$(allGrid[i]).datagrid("getRows");
    $.each(rows,function(i,item){
     relationArrays.push(item);
    })
   }
  
   $.ajax({
  type : "POST",
  url : '../projectController/addRelations',
  data:{"params":JSON.stringify(relationArrays)},
  dataType : 'json',
  cache : false,
  success : function(data) {
   alert(data.msg);
  }
 });

 

2、java代碼

  @RequestMapping("/addRelations")
    public void addRelations(HttpServletRequest request,HttpServletResponse response, HttpSession session) {
     String jsonStr = request.getParameter("params");
     //存儲需要insert的項目人員關系信息
     List<ProjectRelation> relationList=new ArrayList<ProjectRelation>();
  
     ProjectRelation relation=null;
     JSONArray jsonArray = JsonUtil.parseArray(jsonStr);
        for(Object ob : jsonArray){
            JSONObject jObject = (JSONObject) ob;
                relation=new ProjectRelation();
                relation.setProjectId(pId);
                relation.setChargemanId(jObject.getInteger("chargemanId"));
                relation.setGroupId(jObject.getInteger("groupId"));
                relation.setUserId(jObject.getInteger("userId"));
                relation.setProjectRole(jObject.getInteger("projectRole"));
                relationList.add(relation);
          }
     //先查詢項目中所有已有人員信息,
     int result=projectServiceImpl.saveProjectRelations(relationList);
 
     HashMap<String, Object> map = new HashMap<String, Object>();
        try {
            if(result==jsonArray.size()){
                map.put("msg", "關聯信息添加成功");
            }
            else {
                map.put("msg", "關聯信息添加錯誤");
            }
            WriteJsonUtil.writejson(map, response);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "關聯信息添加錯誤");
            WriteJsonUtil.writejson(map, response);
        }
    }

 

3、JSONUtil代碼

   public static JSONArray parseArray(String text){
        JSONArray jsonArray=JSON.parseArray(text);
       
        return jsonArray;
    }

 

具體JsonUtil代碼請從該鏈接下載http://files.cnblogs.com/files/DylanZ/JsonUtil.rar


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM