I’m trying to pass submited form to my page Controller. I’m constructing JSON object like this:
{
"periodId": "1",
"domainId": "46",
"modelTypeId": "1",
"modelGroup": {
"modelGroupName": "123",
"modelGroupDescription": "abc"
}
}
Where I’d like to objects *Id to be passed as Integer and modelGroup as full object. So my goal is somehow make this work:
JS file
jQuery.ajax( "/Models/SaveModel", {
type:"POST",
dataType:'json',
contentType:"application/json",
data:JSON.stringify( output )
} );
Page Controller
@RequestMapping(value = "/SaveModel", method = RequestMethod.POST, headers = {"content-type=application/json"})
public
@ResponseBody
boolean createModel( SettlementModelGroup modelGroup,
Integer periodId,
Integer domainId,
Integer modelTypeId )
{
//process data here
}
Is it possible or do I have to make @RequestBody String object annotation and then parse JSON file?
Spring MVC by default will not do this for you – if you want to use the default approach, you can like you have said create a wrapper type with your
modelGroup,periodId,domainId,modelTypeIdand annotate the wrapper type with@RequestBody.If you absolutely want an approach along the lines of what you have written, an approach will be to :
Create a custom annotation – say
@JsonArgAnnotate the relevant parameters with this annotation
Write a custom HandlerMethodArgumentResolver which will support @JsonArg annotated arguments:
Write logic to parse out the relevant parameter from the request body: