use*_*426 10 java spring jackson spring-boot
我想用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;
}
Run Code Online (Sandbox Code Playgroud)
我发送的JSON对象如下:
{
"userId": 3
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的例外:
WARN 964 --- [XNIO-2 task-7] .wsmsDefaultHandlerExceptionResolver:无法读取HTTP消息:org.springframework.http.converter.HttpMessageNotReadableException:无法读取文档:无法从START_OBJECT反序列化java.lang.Integer的实例令牌在[来源:java.io.PushbackInputStream@12e7333c; line:1,column:1]; 嵌套异常是com.fasterxml.jackson.databind.JsonMappingException:无法在[来源:java.io.PushbackInputStream@12e7333c;中的START_OBJECT标记中反序列化java.lang.Integer的实例.line:1,column:1]
Ali*_*ani 13
显然杰克逊不能将传递的JSON反序列化为Integer.如果您坚持通过请求体发送用户的JSON表示,则应该将其封装userId在另一个bean中,如下所示:
public class User {
private Integer userId;
// getters and setters
}
Run Code Online (Sandbox Code Playgroud)
然后使用该bean作为处理程序方法参数:
@RequestMapping(...)
public @ResponseBody Record getRecord(@RequestBody User user) { ... }
Run Code Online (Sandbox Code Playgroud)
如果你不喜欢创建另一个bean的开销,你可以传递路径变量的userId一部分,例如.为了做到这一点:/getuser/15
@RequestMapping(value = "/getuser/{userId}", method = POST, produces = "application/json")
public @ResponseBody Record getRecord(@PathVariable Integer userId) { ... }
Run Code Online (Sandbox Code Playgroud)
由于您不再在请求正文中发送JSON,因此应删除该consumes属性.
小智 10
Perhaps you are trying to send a request with JSON text in its body from a Postman client or something similar like this:
{
"userId": 3
}
Run Code Online (Sandbox Code Playgroud)
This cannot be deserialized by Jackson since this is not an Integer (it seems to be, but it isn't). An Integer object from java.lang Integer is a little more complex.
For your Postman request to work, simply put (without curly braces { }):
3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60376 次 |
| 最近记录: |