微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AJAX向SpringMVC controller 传JSONArray并将String转换成JSONArray

http://stackoverflow.com/questions/14515785/how-to-convert-json-string-arrray-to-json-array-list


create JSONArray ([{},{},{}]) in JS

var data = [];
data.push({
		"id" : 1,"val" : $('#projectName').val()
	});
	data.push({
		"id" : 2,"val" : $('#description').val()
	});
	data.push({
		"id" : 3,"val" : $('#startdate').val()
	});
	data.push({
		"id" : 4,"val" : STATUS_NOT_START
	});
	var id = 5;
	while($("#" + id).length > 0){
		data.push({
			"id" : id,"val" : $("#" + id).val()
		});
		id++;
	}

ajax pass JSONArray String to Controller:
$.ajax({
		type : "Post",url : "createProject.html",data : "jsonArray=" + JSON.stringify(data) + "&depId=" + depId + "&groId=" + groId + "&objId=" + objId,success : function(response){
			var alertText = "Project " + $('#projectName').val() + " is successfully created! Project ID: " + response;
			adDalert("alert-success",alertText,"#alertdiv");
		},error : function(e){
			var alertText = 'Error: ' + e;
     		adDalert("alert-error","#alertdiv");
		}
	});

Controller将JSONArray String转换成JSONArray
import net.sf.json.JSONArray; JSONException; JSONObject; JSONSerializer; public class TestJson { static void parseProfilesJson(String the_json){ try { JSONArray nameArray =(JSONArray) JSONSerializer.toJSON(the_json); System.out.println(nameArray.size()); for(Object js : nameArray){ JSONObject json = (JSONObject)js; System.out.println(json.get("date")); } } catch (JSONException e) { e.printstacktrace(); } } void main(String[] args) { String s = "[{\"date\":\"2012-04-23\",\"activity\":\"gym\"},{\"date\":\"2012-04-24\",\"activity\":\"walking\"}]"; parseProfilesJson(s); } }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐