Spring form object binding, works when submitted normally. But how to convert to json and use ajax
I have a form when submitted to a controller works fine, the controller signature :
@RequestMapping(value = "/Save", method = RequestMethod.POST)
public ModelAndView save(@ModelAttribute MyDTO myDTO) {}
I have anothe开发者_开发问答r controller method for handling an ajax request with this signature:
@RequestMapping(value = "/Preview", method = RequestMethod.POST)
public ModelAndView preview(@RequestBody MyDTO myDTO) {}
However submitting the serialized form returns this error : org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "myList[0]" (Class myPackage.dto.MyDTO), not marked as ignorable
The javascript/jquery is :
var json = jq("#dtoForm").serializeObject();
json = JSON.stringify(json);
jq.ajax({
cache:false,
type: 'POST',
url: "${Preview}",
data:json,
contentType: "application/json",
success: function(data) {
previewDialog.html(data);
previewDialog.dialog('open');
}
});
What am I missing ? I am confused becuase the form submits fine (the dto is correctly mapped) when not converted json. The dto contains, amongst other things, a list.
Edit if I remove the json = JSON.stringify(json);
as suggested by springsource I get a slightly different error (one of the fields in dto is called "title"):
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized token 'til': was expecting 'null', 'true' or 'false'
In case anyone else has same problem, I got the code from here : http://code.google.com/p/form2js/ included the libs, and changed my code to this :
var json = jq("#dtoForm").toObject(); //the new lib I dl'd from link
json = JSON.stringify(json);
...
//and then to do the same ajax call
However, it is not completely solved as the spring-mvc form creates a hidden form element for each checkbox, which I then delete manually :
delete json._MyBoolean;
A side note, this all seems rather messy - shouldn't spring/jackson be able to convert pojo's to an html form and json in both directions with out all this extra stuff.
(original stack ref to library is here)
精彩评论