springMVC 接收json字符串参数

 1 /**
 2 前台js拼接了一个数组 myparam = [a,b,c]; 在ajax中直接 {"myparam":JSON.stringify(myparam)} 传入springMVC的controller中,在接收端可以这样接收
 3 */
 4 @RequestMapping(value="/aaa")
 5 @ResponseBody
 6 public void aaa(@RequestParam(value="myparam")Object myparam ){ //@RequestParam(value="myparam") 也可以不写,默认就是它
 7     Gson gson = new Gson();
 8     List mylist = gson.fromJson(myparam.toString(),List.class);
 9     for(int i;i<mylist.size();i++){
10         String item = mylist.get(i).toString(); //得到数组的每一个元素
11     }
12         
13 }

上面也可以这样写:

 1 /**
 2 前台js拼接了一个数组 myparam = [a,b,c]; 在ajax中直接 {"myparam":myparam} 传入springMVC的controller中,在接收端可以这样接收
 3 */
 4 @RequestMapping(value="/aaa")
 5 @ResponseBody
 6 public void aaa(String[] myparam ){ //这种写法时,前台不能传json字符串,要直接传数组对象 myparam 不用转JSON.stringify
 7     
 8     for(int i;i<myparam.length;i++){
 9         myparam[i] //得到数组的每一个元素
10     }
11         
12 }
13 //另外如果用ajaxSubmit提交时,可以直接把 myparam = [a,b,c]  中的myparam扔到一个input框的val中,即:$("#inputArr").val(myparam)
14 //然后再直接ajaxSubmit表单提交,效果和上面一样    myparam 会作为一个数组对象被传递到后台。
15 //也就是说不是input框只能提交字符串,扔个 数组对象 进去也是可以的。照样可以提交对象。

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

下面是传递其他类型的json数据,可以参考下

//js定义json对象
            var username = $("#username").val();
            var password = $("#password").val();
            var json = {
                "username" : username,
                "password" : password
            };
$.ajax({
                url : "jsontest",
                type : "POST",
                async : true,
                contentType : "application/json",
                data : JSON.stringify(json),
                dataType : 'json',
                success : function(data) {
                    if (data.userstatus === "success") {
                        $("#errorMsg").remove();
                    } else {
                        if ($("#errorMsg").length <= 0) {
                            $("form[name=loginForm]").append(errorMsg);
                        }
                    }
                }
            });
@RequestMapping("/jsontest")
    public void test(@RequestBody(required=true) Map<String,Object> map  ){
        String username = map.get("username").toString();
        String password = map.get("password").toString();
        System.out.println("username: " + username);
        System.out.println("password: " + password);
    }

这种用map接收的方式要求后台必须用@RequestBody注解,但是这样要求ajax必须用 

contentType : "application/json"

方式,当同一次请求除了传递json类型还传递许多其他的字符串参数时,就或报400错误。这个是个硬伤,要用这种方式,Controller层方法中只能接收一个Json类型的参数,不能再有其他类型的参数。

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

也可以参考下面:

@Controller
@RequestMapping("/admin/Obj")
public class ObjAction {
    /**
     * 前端操作与上面相同
     * @return
     */
    @RequestMapping(value = "/updateAttr")
    @ResponseBody
    public String updateAttr(@RequestBody Map<String, String> map) {
        if(map.containsKey("id"){
            Integer id = Integer.parseInt(map.get("id"));
        }
        if(map.containsKey("objname"){
            String objname = map.get("objname").toString();
        }
        if(map.containsKey("pid"){
            Integer pid = Integer.parseInt(map.get("pid"));
        }
        // 操作 ...
        return "success";
    }
}

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

还可以参考这个:

js代码:

 1 <head>
 2     <title>submitUserList_3</title>
 3     <meta http-equiv="content-type" content="text/html; charset=utf-8">
 4     <script language="JavaScript" src="/js/jquery.min.js" ></script>
 5     <script language="JavaScript" src="/js/jquery.json.min.js" ></script>
 6     <script type="text/javascript" language="JavaScript">
 7         function submitUserList_3() {alert("ok");
 8             var customerArray = new Array();
 9             customerArray.push({id: "1", name: "李四", pwd: "123"});
10             customerArray.push({id: "2", name: "张三", pwd: "332"});
11             $.ajax({
12                 url: "/user/submitUserList_3",
13                 type: "POST",
14                 contentType : 'application/json;charset=utf-8', //设置请求头信息
15                 dataType:"json",
16                 //data: JSON.stringify(customerArray),    //将Json对象序列化成Json字符串,JSON.stringify()原生态方法
17                 data: $.toJSON(customerArray),            //将Json对象序列化成Json字符串,toJSON()需要引用jquery.json.min.js
18                 success: function(data){
19                     alert(data);
20                 },
21                 error: function(res){
22                     alert(res.responseText);
23                 }
24             });
25         }
26     </script>
27 </head>

java代码:

1     @RequestMapping(value = "/submitUserList_3", method ={RequestMethod.POST})
2     @ResponseBody
3     public String submitUserList_3(@RequestBody List<User> users)
4             throws Exception{
5         String result = "";
6         if(users == null || users.size() <= 0){ return "No any ID.中文"; }
7         result = this.showUserList(users);
8         return result;
9     }
原文地址:https://www.cnblogs.com/libin6505/p/6812843.html