JsonMappingException:无法从 START_OBJECT 令牌中反序列化 java.lang.Integer 实例

问题描述 投票:0回答:3

我想使用 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
}

这是我得到的例外:

警告 964 --- [ XNIO-2 任务 7] .w.s.m.s.DefaultHandlerExceptionResolver:无法读取 HTTP 信息: org.springframework.http.converter.HttpMessageNotReadableException: 无法读取文档:无法反序列化实例 java.lang.Integer 超出 START_OBJECT 标记,位于 [来源: java.io.PushbackInputStream@12e7333c;行:1,列:1];嵌套的 例外是 com.fasterxml.jackson.databind.JsonMappingException:可以 不反序列化 START_OBJECT 中的 java.lang.Integer 实例 令牌位于[来源:java.io.PushbackInputStream@12e7333c;行:1, 栏目:1]

java spring spring-boot jackson
3个回答
24
投票

显然 Jackson 无法将传递的 JSON 反序列化为

Integer
。如果您坚持通过请求正文发送 User 的 JSON 表示形式,则应将
userId
封装在另一个 bean 中,如下所示:

public class User {
    private Integer userId;
    // getters and setters
}

然后使用该 bean 作为处理程序方法参数:

@RequestMapping(...)
public @ResponseBody Record getRecord(@RequestBody User user) { ... }

如果您不喜欢创建另一个 bean 的开销,您可以将

userId
作为 Path Variable 的一部分传递,例如
/getuser/15
。为了做到这一点:

@RequestMapping(value = "/getuser/{userId}", method = POST, produces = "application/json")
public @ResponseBody Record getRecord(@PathVariable Integer userId) { ... }

由于您不再在请求正文中发送 JSON,因此您应该删除该

consumes
属性。


16
投票

也许您正在尝试从 Postman 客户端或类似的东西发送正文中包含 JSON 文本的请求:

{
 "userId": 3
}

这不能被杰克逊反序列化,因为这不是一个整数(看起来是,但事实并非如此)。 java.lang 中的 Integer 对象 Integer 稍微复杂一些。

为了使您的 Postman 请求正常工作,只需简单地输入(不带花括号 { }):

3

0
投票

我遇到了类似的问题,我这样做了(@RequestBody JsonNode json)。这可确保信息不会在 url 中传递。

当你想将值用作数字时,只需使用:json.asInt();

© www.soinside.com 2019 - 2024. All rights reserved.