我想用Spring Boot编写一个小而简单的REST服务。下面是REST服务代码:
@Async
@RequestMapping(value = "/getuser", method = POST, consumes = "application/json", produces = "application/json")
public @ResponseBody Record getRecord(@RequestBody Integer userId) {
Record result = null;
// Omitted logic
return result;
}我发送的JSON对象如下:
{
"userId": 3
}下面是我得到的一个例外:
org.springframework.http.converter.HttpMessageNotReadableException: WARN 964 - XNIO-2 task-7 .w.s.m.s.DefaultHandlerExceptionResolver :无法读取
消息:XNIO无法读取文档:无法从源: java.io.PushbackInputStream@12e7333c;的START_OBJECT标记反序列化java.lang.Integer的实例;行: 1,列: 1;嵌套异常是com.fasterxml.jackson.databind.JsonMappingException:无法反序列化位于源: java.io.PushbackInputStream@12e7333c;的java.io.PushbackInputStream@12e7333c标记之外的java.lang.Integer的实例。行: 1,列: 1
发布于 2016-05-27 05:28:53
显然,Jackson不能将传递的JSON反序列化为Integer。如果您坚持要通过请求正文发送用户的JSON表示,则应该将userId封装在另一个bean中,如下所示:
public class User {
private Integer userId;
// getters and setters
}然后使用该bean作为处理程序方法参数:
@RequestMapping(...)
public @ResponseBody Record getRecord(@RequestBody User user) { ... }如果您不喜欢创建另一个bean的开销,您可以将userId作为Path变量的一部分进行传递,例如/getuser/15。为了做到这一点:
@RequestMapping(value = "/getuser/{userId}", method = POST, produces = "application/json")
public @ResponseBody Record getRecord(@PathVariable Integer userId) { ... }由于您不再在请求正文中发送JSON,因此应该删除该consumes属性。
发布于 2018-10-14 08:46:34
您可能正在尝试从Postman客户端或类似以下内容发送正文中包含JSON文本的请求:
{
"userId": 3
}这不能被Jackson反序列化,因为它不是一个Integer (看起来是,但它不是)。来自java.lang Integer的Integer对象稍微复杂一些。
要让您的Postman请求正常工作,只需添加(不带大括号{ }):
3https://stackoverflow.com/questions/37471005
复制相似问题