将JSON数据传递到Spring MVC控制器 [英] passing JSON data to a Spring MVC controller
本文介绍了将JSON数据传递到Spring MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要发送一个JSON字符串到Spring MVC控制器。但我不
有任何形式绑定到它,我只需要发送一个简单的JSON数据到Controller类。我正在进行jQuery AJAX调用控制器方法如下面的代码。
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 ");
}
});
但是如何在Controller方法中检索呢?不是表单提交)。
But how do I retrieve it in the Controller method?(Note: It is just plain JSON data and not a form submission).
推荐答案
添加以下依赖项
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.7</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.7</version>
</dependency>
修改请求如下
$.ajax({
url:urlName,
type:"POST",
contentType: "application/json; charset=utf-8",
data: jsonString, //Stringified Json Object
async: false, //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
cache: false, //This will force requested pages not to be cached by the browser
processData:false, //To avoid making query String instead of JSON
success: function(resposeJsonObject){
// Success Message Handler
}
});
控制器端
@RequestMapping(value = urlPattern , method = RequestMethod.POST)
public @ResponseBody Person save(@RequestBody Person jsonString) {
Person person=personService.savedata(jsonString);
return person;
}
@RequestBody
将Json对象隐藏到java
@ResponseBody
- 将Java对象转换为json
@RequestBody
- Covert Json object to java
@ResponseBody
- convert Java object to json
这篇关于将JSON数据传递到Spring MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文