SPRINGMVC receive JSON string parameters

Source: Internet
Author: User
Tags tojson

1 /**2 The foreground JS stitching an array myparam = [a,b,c]; in Ajax directly {"Myparam": Json.stringify (Myparam)} in the controller that is passed in Springmvc, the receiver can receive 3 */4@RequestMapping (value= "/AAA")5 @ResponseBody6  Public voidAAA (@RequestParam (value= "Myparam") Object Myparam) {//@RequestParam (value= "Myparam") can also not write, the default is it7Gson Gson =NewGson ();8List mylist = Gson.fromjson (myparam.tostring (), list.class);9      for(intI;i<mylist.size (); i++){TenString item = mylist.get (i). toString ();//get each element of an array One     } A          -}

The above can also be written like this:

1 /**2 The front desk JS stitching an array myparam = [a,b,c]; in Ajax directly {"Myparam": Myparam} in the controller that incoming SPRINGMVC, the receiver can receive this3 */4@RequestMapping (value= "/AAA")5 @ResponseBody6  Public voidAAA (string[] myparam) {//in this writing, the foreground cannot pass the JSON string, to pass the array object directly myparam not to go json.stringify7     8      for(inti;i<myparam.length;i++){9Myparam[i]//get each element of an arrayTen     } One          A } - //In addition, if you submit with Ajaxsubmit, you can simply throw the myparam in myparam = [A,b,c] into the Val of the input box, which is: $ ("#inputArr"). Val (myparam) - //and then directly ajaxsubmit the form submission, the effect is the same as the above Myparam will be passed as an array object to the background.  the //that is, not the input box can only submit strings, throwing the array of objects in is also possible. You can still commit the object. 

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

Here are some other types of JSON data that you can refer to below

//js defining JSON Objects            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")    publicvoid Test (@RequestBody (required=true ) map<string,object> Map  ) {        = Map.get ("username"). toString ();         = Map.get ("password"). toString ();        System.out.println ("username:" + username);        System.out.println ("Password:" + password);    }

This method of receiving the map requires that the background must be annotated with @requestbody, but this requires Ajax to use

"Application/json"

, a 400 error is reported when the same request passes a number of other string arguments, in addition to passing the JSON type. This is a mishap, in this way, the controller layer method can only receive a JSON-type parameter, no longer have other types of parameters.

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

You can also refer to the following:

@Controller @requestmapping ("/admin/obj") Public classobjaction {/*** Front-end operation same as above *@return     */@RequestMapping (Value= "/updateattr") @ResponseBody PublicString 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")); }        //operation ...        return"Success"; }}

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

You can also refer to this:

JS Code:

12<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         functionSubmituserlist_3 () {alert ("OK");8             varCustomerarray =NewArray ();9Customerarray.push ({id: "1", Name: "John Doe", PWD: "123"});TenCustomerarray.push ({ID: "2", Name: "Zhang San", pwd: "332"}); One $.ajax ({ AURL: "/user/submituserlist_3", -Type: "POST", -ContentType: ' Application/json;charset=utf-8 ',//Set Request header information theDataType: "JSON", -                 //data:JSON.stringify (Customerarray),//JSON object serialized into JSON string, json.stringify () primitive Ecological Method -Data: $.tojson (Customerarray),//serializes a JSON object into a JSON string, ToJSON () requires a reference jquery.json.min.js -Successfunction(data) { + alert (data); -                 }, +Errorfunction(res) { A alert (res.responsetext); at                 } -             }); -         } -</script> -

Java code:

1@RequestMapping (value = "/submituserlist_3", method ={requestmethod.post})2 @ResponseBody3      PublicString Submituserlist_3 (@RequestBody list<user>users)4             throwsexception{5String result = "";6         if(Users = =NULL|| Users.size () <= 0) {return"No any ID. Chinese"; }7result = This. Showuserlist (users);8         returnresult;9}

SPRINGMVC receive JSON string parameters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.