JSON发布到Spring Controller

嗨我在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; } 

我的模型测试看起来像:

 public class Test implements Serializable { private static final long serialVersionUID = -1764970284520387975L; public String name; public Test() { } } 

通过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. 

我importjackson图书馆。 我的GET方法运行正常。 我不知道我做错了什么。 我很感激任何建议。

使用将JSON对象转换为JSON String

JSON.stringify({ “名”: “测试名”})

或手动。 @RequestBody期待json字符串而不是json对象。

注意:stringify函数有一些IE版本的问题,它会起作用

validation您的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 } }); 

调节器

 @RequestMapping(value = urlPattern , method = RequestMethod.POST) public @ResponseBody Test addNewWorker(@RequestBody Test jsonString) { //do business logic return test; } 

@RequestBody -Covert Json对象到java

@ResponseBody – 将Java对象转换为json

尝试使用application / *代替。 并使用JSON.maybeJson()来检查控制器中的数据结构。

如果要将json用作http请求和响应,请执行以下操作。 所以我们需要在[context] .xml中进行更改

            

将HistoryJackson2HttpMessageConverter映射到RequestMappingHandlerAdapter messageConverters,以便Jackson API启动并将JSON转换为Java Bean,反之亦然。 通过这种配置,我们将在请求体中使用JSON,我们将在响应中接收JSON数据。

我还为控制器部分提供了小代码片段:

  @RequestMapping(value = EmpRestURIConstants.DUMMY_EMP, method = RequestMethod.GET) public @ResponseBody Employee getDummyEmployee() { logger.info("Start getDummyEmployee"); Employee emp = new Employee(); emp.setId(9999); emp.setName("Dummy"); emp.setCreatedDate(new Date()); empData.put(9999, emp); return emp; } 

所以在上面的代码中,emp对象将直接转换为json作为响应。 同样也会发生在post上。

您需要为模型Test类中定义的所有字段包含getter和setter –

 public class Test implements Serializable { private static final long serialVersionUID = -1764970284520387975L; public String name; public Test() { } public String getName() { return name; } public void setName(String name) { this.name = name; } }