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

前端之家收集整理的这篇文章主要介绍了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); } }

猜你在找的SpringMVC相关文章