本文介绍了JsonMappingException:无法从START_OBJECT标记中反序列化java.lang.Integer的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Spring Boot编写一个小而简单的REST服务。
这是REST服务代码:

I wanted to write a small and simple REST service using Spring Boot.Here is the REST service code:

@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对象如下:

The JSON object I sent is the following:

{
    "userId": 3
}

这是我得到的例外:


推荐答案

显然杰克逊无法反序列化将JSON传递给 Integer 。如果您坚持通过请求正文发送用户的JSON表示,则应将 userId 封装在另一个bean中,如下所示:

Obviously Jackson can not deserialize the passed JSON into an Integer. If you insist to send a JSON representation of a User through the request body, you should encapsulate the userId in another bean like the following:

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

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

Then use that bean as your handler method argument:

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

如果你不喜欢创建另一个bean的开销,你可以通过 userId 作为路径变量的一部分,例如 /的getUser / 15 。为了做到这一点:

If you don't like the overhead of creating another bean, you could pass the userId as part of Path Variable, e.g. /getuser/15. In order to do that:

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

由于您不再在请求正文中发送JSON,因此应删除消耗属性。

Since you no longer send a JSON in the request body, you should remove that consumes attribute.

这篇关于JsonMappingException:无法从START_OBJECT标记中反序列化java.lang.Integer的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 16:27
查看更多