【问题标题】:How to send JSON in Spring?如何在 Spring 中发送 JSON?
【发布时间】:2013-03-01 15:00:36
【问题描述】:

我试图找到如何在 Spring 中编写以从 REST 客户端发布 JSON。例如,我写道:

@RequestMapping(value = "/{userId}/add", method = RequestMethod.POST, headers = {"content-type=application/json"})
@ResponseBody
public Map<String, String> saveUser(@RequestBody User user, BindingResult result) { 
    Map<String, String> jsonResponse = new HashMap<String, String>();
    if (result.hasErrors()) {
        jsonResponse.put("Message", "Can't add the user");
        jsonResponse.put("Code", "401");
        return jsonResponse;
    }
    userService.addUser(user);
    jsonResponse.put("Message", "Success add User");
    jsonResponse.put("Code", "200");
    return jsonResponse;
}

从 Firefox REST 客户端对其进行了最终测试。但我看到了 404 错误。我究竟做错了什么?感谢您的帮助。

【问题讨论】:

  • 你发送给服务器的 HTTP 请求的内容是什么?
  • 例如我试过这样 { "id": 7, "token": null, "nameUser": "Mulder Fox", "dateBirth": "25.10.1975", "role" :“ROLE_USER”,“职位”:“职位”,“电子邮件”:“fox@gmail.com”,“登录”:“muldfox”,“电话”:“+12356565”,“地址”:null,“组织": null, "兴趣": null }
  • 有两种可能性:1) Spring 无法解析您的某个字段,2) JSON 对象中的字段与 User 对象中的字段不匹配,3) 您的 URL 可能是错的。如果您在问题中发布整个 HTTP 请求和您的 User 类,也许我们可以缩小范围。此外,如果您的日志中有异常堆栈跟踪,那也会很有帮助。
  • userId 在您的 RequestMapping 路径中解析为什么?
  • 我检查了一个 URL 并且它是正确的,但是我有一个堆栈跟踪:org.springframework.web.servlet.PageNotFound - 没有为 servlet 请求找到匹配的处理程序方法:路径'/user/2/add ',方法'POST',参数map[[empty]]

标签: json spring rest jakarta-ee


【解决方案1】:

首先,如果您的请求的 URI 以“/user/2/add”结尾,它不会映射到您的方法,该方法被映射为“/{userId}/add”。这将导致您收到 HTTP 404 错误。相反,如果“userId”为 2,您的 URI 应以“/2/add”结尾。

其次,使用 @RequestBody 注释 User 参数对于复杂的 User 类型是不够的。您需要将 JSON 请求正文转换为 User 对象。您可以使用MappingJacksonHttpMessageConverter 完成此操作。通过声明这种类型的 bean,您可以使用 Jackson 的注解来控制 JSON 如何解析为 User 属性。

【讨论】:

  • 不,我做对了。 @RequestBody 就足够了,因为我使用的是 Spring 3.0.x。问题是我测试的时候没有在request header中使用header。
猜你喜欢
  • 1970-01-01
  • 2016-07-23
  • 2015-10-25
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 1970-01-01
相关资源
最近更新 更多