首页 > 程序开发 > web前端 > JavaScript >

Spring 接收转换 jquery ajax json数组字符串

2014-08-14

1、ajax发送json字符串 组建对象var student = new Object(); student name = "柯乐义 "; student age = "25 "; student location = "广州 "; var student2 = new Object(); student2 name =

1、ajax发送json字符串

组建对象

var student = new Object();
student.name = "柯乐义";
student.age = "25";
student.location = "广州";

var student2 = new Object();
student2.name = "柯范德萨";
student2.age = "45";
student2.location = "FDA";

myList.push(student);
myList.push(student2);
ajax发送,注意datatype ,type 等的正确赋值,使用jsonstringify对对象进行模型转换,转换后的字符串可以在http://www.bejson.com/ 进行在线json格式检查正确与否。

            $.ajax({ //请求登录处理页
                        url:url, //登录处理页
                        dataType:"json",
                        data: JSON.stringify(myList),
			type: "POST",
                        headers : {
					 'Accept' : 'application/json',
					 'Content-Type' : 'application/json'
				   },
					
                        success:function (strValue) { //登录成功后返回的数据
                            //根据返回值进行状态显示
                            //alert(strValue);
                            if (strValue.successful == "true") {
                                alert("发送成功@@");
                            }
                            else {
                                alert("发送失败@@");
                            }

                        },

                        error:function () {

                            alert("请检查是否有参数错误@@");
                        }
                    });


2、spring进行配置


配置requestbody进行json字符串的数组转换

    @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");

	}

注意在springmvc-servlet.xml进行如下配置:json转化器配置

	
		
			
				text/html;charset=UTF-8
				application/json
			
		
	

	
		
			
				
				
				

			
		
		
	

class SnapInfo
类SnapInfo定义的时候记得要构件一个空函数的构造函数,不然会报一下错误!

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object



参考文档:
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

相关文章
最新文章
热点推荐