JsonMappingException:无法从START_OBJECT标记中反序列化java.lang.Integer的实例

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

这是我得到的例外:

WARN 964 — [ XNIO-2 task-7]
.w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP
message:
org.springframework.http.converter.HttpMessageNotReadableException:
Could not read document: Can not deserialize instance of
java.lang.Integer out of START_OBJECT token at [Source:
java.io.PushbackInputStream@12e7333c; line: 1, column: 1]; nested
exception is com.fasterxml.jackson.databind.JsonMappingException: Can
not deserialize instance of java.lang.Integer out of START_OBJECT
token at [Source: java.io.PushbackInputStream@12e7333c; line: 1,
column: 1]

最佳答案
显然杰克逊不能将传递的JSON反序列化为整数.如果您坚持通过请求体发送用户的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,因此应删除该使用属性.

转载注明原文:JsonMappingException:无法从START_OBJECT标记中反序列化java.lang.Integer的实例 - 代码日志