我正在使用spring mvc,我需要使用ajax从我的jsp将JSON数组传递给spring控制器。任何人都可以帮我解决如何在控制器中传递,映射和访问JSON数组。
(JSON数组就像[{'Name':'ksjdfh','Email':'sdfkhg'},{'Name':'ksjdfh','Email':'sdfkhg'},{'Name':'ksjdfh','Email':'sdfkhg'}])
答案 0 :(得分:0)
这里有一篇关于如何做到这一点的帖子:Parsing JSON in Spring MVC using Jackson JSON。
基本上,您需要一个模型对象来将JSON反序列化为。
请注意(正如Gunslinger所说)你也可以像传统的其他参数一样将JSON作为字符串传递。在GET请求中,这将导致URL(不使用cookie),如localhost/foo?bar=[your_json_as_string]
另请注意,您使用AJAX对您的问题并不重要。
答案 1 :(得分:0)
这是我的解决方案:
我们要发送的js类:
function Event(id, name) {
this.starttime = '';
this.endtime = '';
this.shiftUsers = [];
this.name = name
this.id = id;
}
填充数组之后:
var shifts = [];
shifts.push(new Event(newid, current_name));
Ajax部分:
$(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);
}
});
});
和java部分,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;
}
我们期望js,setter和getter的课程必要:
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;
}
}