无法从START_OBJECT令牌中反序列化`java.lang.Boolean`的实例

时间:2019-08-16 08:20:42

标签: java json rest spring-boot jackson-databind

这是我的Put请求的Controller映射:

@PutMapping("/voteForPostByUser")
    public String vote(@RequestParam(value = "postId", required = 
true) String postId, @RequestParam(value = "userId", required = true) 
Integer userId, @RequestBody Boolean vote) {

        BlogPostVoteDTO blogPostVoteDTO = new BlogPostVoteDTO 
(postId, userId, vote);
        return 
this.blogPostService.updateBlogPostVotes(blogPostVoteDTO);  
}

当我从POSTMAN运行以下请求时:

http://localhost:8082/microblog/api/voteForPostByUser?postId=5d564a2638195729900df9a6&userId=5

Request Body:
{
        "vote" : true
    }

我收到以下异常

"status": 400,
    "error": "Bad Request",
    "message": "JSON parse error: Cannot deserialize instance of 
`java.lang.Boolean` out of START_OBJECT token; nested exception is 
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot 
deserialize instance of `java.lang.Boolean` out of START_OBJECT token\n 
at [Source: (PushbackInputStream); line: 1, column: 1]",
    "trace": 
"org.springframework.http.converter.HttpMessageNotReadableException: JSON 
parse error: Cannot deserialize instance of `java.lang.Boolean` out of 
START_OBJECT token; nested exception is 
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot 
deserialize instance of `java.lang.Boolean` out of START_OBJECT token\n 
at [Source: (PushbackInputStream); line: 1, column: 1]\r\n\tat 

我可能很简单,但是我不明白我想念的是什么吗?

4 个答案:

答案 0 :(得分:2)

您只需要发送truefalse作为请求的正文,不需要花括号或键值结构

答案 1 :(得分:2)

为您的有效负载创建一个新类:

  class Payload {
    Boolean vote;
    // maybe some getters/setter here
  }

并将其用作您的RequestBody

@PutMapping("/voteForPostByUser")
public String vote(@RequestParam(value = "postId", required = true) String postId, @RequestParam(value = "userId", required = true) Integer userId, @RequestBody Payload payload) {
    boolean vote = payload.vote; //or payload.getVote()
    BlogPostVoteDTO blogPostVoteDTO = new BlogPostVoteDTO(postId, userId, vote);
    return this.blogPostService.updateBlogPostVotes(blogPostVoteDTO);  
}

答案 2 :(得分:1)

我像这样用true或false尝试邮递员。没关系。

enter image description here

答案 3 :(得分:0)

您期望@RequestBody Boolean vote中有一个布尔值,但是JSON发送文本。您可以按照建议使用Payload类,但也可以简单地更改控制器以期望像这样的@RequestBody String vote字符串,并使用Boolean.valueOf(vote)将该字符串转换为布尔值,以便可以在需要的地方使用它它。