问题
I am working on spring mvc and I need to pass JSON array to spring controller from my jsp using ajax. Can anyone help me out how to pass, map and access JSON array in controller.
(JSON array would be like [{'Name':'ksjdfh','Email':'sdfkhg'},{'Name':'ksjdfh','Email':'sdfkhg'},{'Name':'ksjdfh','Email':'sdfkhg'}])
回答1:
There is a post on how to do that here: Parsing JSON in Spring MVC using Jackson JSON.
Basically, you need a model object to deserialize the JSON to.
Note that (as Gunslinger says) you could also just pass the JSON as string as you would any other parameter. In a GET request that would result in an URL (without use of cookies) like localhost/foo?bar=[your_json_as_string]
Also note that you are using AJAX is not at all essential to your problem.
回答2:
This is my solution:
js class that we want to send:
function Event(id, name) {
this.starttime = '';
this.endtime = '';
this.shiftUsers = [];
this.name = name
this.id = id;
}
After that fill array:
var shifts = [];
shifts.push(new Event(newid, current_name));
Ajax part:
$(document).on('click', '#test1', function(e) {
console.log('Test ajax save');
$.ajax({
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
type: "POST",
url: "ajaxCreateShiftKind2.htm",
dataType: "json",
data: JSON.stringify(shifts),
contentType: 'application/json',
success: function(html) {
alert(html);
}
});
});
And java part, recive:
@RequestMapping(value = "/ajaxCreateShiftKind2", method = RequestMethod.POST)
public @ResponseBody
Map<String, Object> ajaxCreateShiftKind2(HttpServletRequest request) {
Map<String, Object> myModel = new HashMap<String, Object>();
//org.codehaus.jackson.map.ObjectMapper
ObjectMapper om = new ObjectMapper();
//Input input = mapper.readValue( request.getInputStream() , Class Input... );
Event[] se;
try {
se = om.readValue(request.getInputStream(), Event[].class);
} catch (Exception e) {
se = null;
}
myModel.put("ajaxResult", 1);
myModel.put("ajaxMessage", "Added succesful");
myModel.put("ajaxShiftKind", "Hello world!");
myModel.put("ajaxData", se);
return myModel;
}
And class that we expect from js, setters and getters are necessary:
public class Event {
int id;
String name, endtime, starttime;
int[] shiftUsers;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStarttime() {
return starttime;
}
public void setStarttime(String Starttime) {
this.starttime = Starttime;
}
public String getEndtime() {
return endtime;
}
public void setEndtime(String Endtime) {
this.endtime = Endtime;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setShiftUsers(int[] shiftUsers) {
this.shiftUsers = shiftUsers;
}
public int[] getShiftUsers() {
return this.shiftUsers;
}
}
来源:https://stackoverflow.com/questions/17987234/passing-json-array-from-javascript-to-spring-mvc-controller