I need to send a JSON string to Spring MVC controller.But I do not have any form bindings to it , I just need to send a plain JSON data to Controller class.I am making jQuery AJAX call to the Controller method like the below code.
$.ajax ({
url: "./save",
type: "POST",
data: JSON.stringify(array),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(){
alert("success ");
}
});
But how do I retrieve it in the Controller method?(Note: It is just plain JSON data and not a form submission).
You can stringify the JSON Object with JSON.stringify(jsonObject) and receive it on controller as String.
In the Controller, you can use the javax.json to convert and manipulate this.
Download and add the .jar to the project libs and import the JsonObject.
To create an json object, you can use
To read it from String, you can use
Add the following dependencies
Modify request as follows
Controller side
@RequestBody
- Covert Json object to java@ResponseBody
- convert Java object to jsonHtml
Controller
Dao