How to pass a JSON array to Spring-MVC?
I am trying to find a way to pass a array of objects in JSON to Spring-MVC(Java)..
below is my javascript that setups the two arrays and makes the call:
function doAjaxPost() {
var inData = {};
inData.name = ['kurt','johnathan'];
inData.education = ['GSM','HardKnocks'];
htmlStr = JSON.stringify(inData);
alert(htmlStr);
$.post( contexPath + "/AddUser.htm", inData, function(outData, outStatus){
alert(outStatus);
});
};
Here is my Java (Spring-MVC) Controller:
@RequestMapping(value="/AddUser.htm",method=RequestMethod.POST)
public @ResponseBody JsonResponse addUser(@ModelAttribute(value="user") User user, BindingResult result ){
JsonResponse res = new JsonResponse();
ValidationUtils.rejectIfEmpty(result, "name", "Name can not be empty.");
ValidationUtils.rejectIfEmpty(result, "education", "Educatioan not be empty");
if(!result.hasErrors()){
userList.add(user);
res.setStatus("SUCCESS");
res.setResult(userList);
}else{
res.setStatus("FAIL");
res.setResult(result.getAllErrors());
}
return res;
}
this is the bean I am using:
public class User {
private String name = null;
private String education = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
}
please let me know the right what to get this working... this is the error I am getting.. SEVERE: Servlet.service() for servlet Spring MVC Dispatcher Servlet threw exception org.springframework.beans.InvalidPropertyException: Invalid property 'education[]' of bean class [com.raistudies.domain.User]: Property referenced in indexed property path 'education[]' is neither an array nor a List nor a Map; returned value was [[Ljava.lang.String;@6fef3212]
Seems like the education property in your JSON is an array, but in your POJO it's a String
If you change
to
It should work, you'll also have to do the same thing for the name.