use*_*655 12 java spring json spring-mvc
嗨,我在Spring中开始使用Web Services,所以我正在尝试在Spring + JSON + Hibernate中开发小型应用程序.我在HTTP-POST方面遇到了一些问题.我创建了一个方法:
@RequestMapping(value="/workers/addNewWorker", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
@ResponseBody
public String addNewWorker(@RequestBody Test test) throws Exception {
String name = test.name;
return name;
}
Run Code Online (Sandbox Code Playgroud)
我的模型Test看起来像:
public class Test implements Serializable {
private static final long serialVersionUID = -1764970284520387975L;
public String name;
public Test() {
}
}
Run Code Online (Sandbox Code Playgroud)
通过POSTMAN,我只发送JSON {"name":"testName"},我总是得到错误;
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
Run Code Online (Sandbox Code Playgroud)
我进口杰克逊库.我的GET方法运行正常.我不知道我做错了什么.我很感激任何建议.
Vin*_*ran 26
使用将JSON对象转换为JSON String
JSON.stringify({ "名": "测试名"})
或手动.@RequestBody期待json字符串而不是json对象.
注意:stringify函数有一些IE版本的问题,它会起作用
验证您的POST请求的ajax请求的语法.processData: ajax请求中需要false属性
$.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 Action
}
});
Run Code Online (Sandbox Code Playgroud)
调节器
@RequestMapping(value = urlPattern , method = RequestMethod.POST)
public @ResponseBody Test addNewWorker(@RequestBody Test jsonString) {
//do business logic
return test;
}
Run Code Online (Sandbox Code Playgroud)
@RequestBody -Cove Json对象到java
@ResponseBody - 将Java对象转换为json
| 归档时间: |
|
| 查看次数: |
88941 次 |
| 最近记录: |