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

来源:互联网 发布:建网站做淘宝客 编辑:程序博客网 时间:2024/06/14 21:05

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", alertText, "#alertdiv");}});

Controller将JSONArray String转换成JSONArray

import net.sf.json.JSONArray;import net.sf.json.JSONException;import net.sf.json.JSONObject;import net.sf.json.JSONSerializer;public class TestJson {    public 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();            }        }    public static void main(String[] args) {        String s = "[{\"date\":\"2012-04-23\",\"activity\":\"gym\"},{\"date\":\"2012-04-24\",\"activity\":\"walking\"}]";        parseProfilesJson(s);    }}


0 0