I'm trying to pass data to my controller using Ajax and JSON.
I've got an HTML table and I've got to send multiple coordinates of that table to my controller. So I made a Javascript array containing anonymous objects of this kind :
{
DAY: someIndex,
HOUR: someOtherIndex
}
and let this array be called coordinates
, I serialized it like this:
JSON.stringify(coordinates)
so then in an ajax call (type: POST
) I used data: JSON.stringify(coordinates)
.
In my document ready I used :
$.ajaxSetup({
headers : {
Accept : "application/json; charset=utf-8"
}
});
And my controller looks like this:
@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public @ResponseBody
String update(@PathVariable int id, @RequestBody String coordinates, HttpServletResponse response) {
// Do something here to convert it in my complex structure
}
However I don't know what the type should be for the parameter coordinates
.
I'm using GSON
. And I wasn't able to deserialize it easily. I tried using this solution, but it wouldn't work. (Kept asking to cast types for some reason.)
Since I didn't think it'd be possible to deserialize this correctly, I tried to serialize the coordinates as another format (just a JSON array of strings where the coordinates are split by a token (;) here
So my array the javascript objects are created like this in a foreach
:
coordinates.push( someIndex.toString() + ";" + someOtherIndex.toString() );
And I kept the stringify part.
So now when I POST
the data to my controller, I output the value with System.out.println(coordinates)
and the output looks weird.
%5B%220%3B8%22%5D=
for this object in the Javascript console : ["0;8"]
.
So my questions :
- Is this a good approach?
- Is it possible to deserialize a JSON array into some java types? Such as
List<Coordinate>
? ( I've tried using this type instead ofString
in my controller, but it would give me an error415 - Unsupported media type
) - If I'm using the String approach, is there a way to translate that gibberish into something I want?