Spring receives and converts jquery ajax json array strings
1. ajax sends a json string
Build object
Var student = new Object (); student. name = "Ke leyi"; student. age = "25"; student. location = "Guangzhou"; var student2 = new Object (); student2.name = "Ke fandesa"; student2.age = "45"; student2.location = "FDA"; myList. push (student); myList. push (student2 );
Ajax send, pay attention to datatype, type, etc. correct value, use jsonstringify to convert the object model, the converted string can be in the http://www.bejson.com/online json format check correct or not.
$. Ajax ({// url of the Request logon processing page: url, // dataType: "json", data: JSON. stringify (myList), type: "POST", headers: {'accept': 'application/json', 'content-type': 'application/json'}, success: function (strValue) {// data returned after successful logon // The status is displayed based on the returned value // alert (strValue); if (strValue. successful = "true") {alert ("sent successfully @");} else {alert ("failed to send @") ;}}, error: function () {alert ("Please check for parameter errors @@");}});
2. Configure spring
Configure requestbody to convert arrays of json strings
@RequestMapping(value="/upload",produces="application/json") @ResponseBody public String login(HttpServletRequest req, HttpServletResponse reponse, String from,String id,@RequestBody SnapInfo[] apList) throws UnsupportedEncodingException { String result; logger.debug("start upload!"+from + ","+id); logger.debug(apList.length); result = JsonUtil.SendJsonResponse(true, "success"); reponse.setContentType("text/html; charset=utf-8"); reponse.setCharacterEncoding("utf-8"); return new String(result.getBytes("utf-8"), "iso-8859-1");}
Note the following configuration in the springmvc-servlet.xml: json converter Configuration
Text/html; charsets = UTF-8
Application/json
class SnapInfo
Remember to build an empty function constructor when defining the SnapInfo class. Otherwise, an error will be reported!
JsonMappingException: No suitable constructor found for type [simple type, class]: can not instantiate from JSON object
Reference:
http://www.bejson.com/
http://www.w3school.com.cn/jquery/ajax_post.asp
http://keleyi.com/a/bjac/8p778pqo.htm
http://stackoverflow.com/questions/7625783/jsonmappingexception-no-suitable-constructor-found-for-type-simple-type-class
http://seaboycs.iteye.com/blog/1997635
http://greatpwx.iteye.com/blog/1974150