I need to POST a request via jQuery.ajax() to a Spring MVC controller URL mapped method and receive a response; both request and response data is in JSON format.
Ajax call would be something like this:
$.ajax({
url: "/panelsData",
dataType: "json",
data: { "id": 1, "panels": [ "View1", "View2", "View3" ] },
success: function(data) {...}
});
Spring MVC controller URL mapped method:
@RequestMapping(value="/panelsData", method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value=HttpStatus.OK)
@ResponseBody
public List<PanelData> getPanelsDataById(
@RequestParam("id") BigDecimal id,
@RequestParam("panels") List<String> panelsList) {
// Process list of Strings corresponding to panel view names
// and return a list of PanelData objects (in JSON format).
}
The first problem I faced was that the client (browser) failed with error code 400 (Bad Request). So, I JSON.stringify'ed the array in the ajax call:
data: { "id": 1, "panels": JSON.stringify([ "View1", "View2", "View3" ]) },
This time, the request was successfully received by Spring MVC. But something was amiss with the list of String values. When I examined the values, here's what I saw:
panelsList[0] = ""[View1""
panelsList[1] = ""View2""
panelsList[2] = ""View3]""
What?! I was expecting these values:
panelsList[0] = "View1"
panelsList[1] = "View2"
panelsList[2] = "View3"
Am I incorrectly serializing (or de-serializing) the values? Given that the exchange of data must all be JSON, and that I am using the Jackson library, I was expecting that receiving an ID and a list of String values from the client in JSON should not be all that difficult. I know the Jackson library configuration is perfect, because the JSON responses returned by the other methods are correctly formed.