我需要向 Spring MVC Controller 发送一个 JSON 字符串。但我不需要 有任何表单绑定(bind),我只需要将纯 JSON 数据发送到 Controller 类。我正在对 Controller 方法进行 jQuery AJAX 调用,如下面的代码。
$.ajax ({
url: "./save",
type: "POST",
data: JSON.stringify(array),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(){
alert("success ");
}
});
但是如何在 Controller 方法中检索它?(注意:它只是纯 JSON 数据,而不是表单提交)。
最佳答案
添加以下依赖项
<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
}
});
Controller 端
@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
关于json - 将 JSON 数据传递给 Spring MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18524524/