为什么这个Spring Boot应用程序会对post请求抛出异常?

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

控制器:-

@RestController
public class MyController {

private String url = "https://scoreboard-backend-dev.herokuapp.com/scoreBoard";

@Autowired
private RestTemplate restTemplate;

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}

@PostMapping("/add/score")
public ScoreBoard addScore(@RequestBody ScoreBoard scoreBoard){
    ResponseEntity<ScoreBoard> responseEntity =  restTemplate
                       .postForEntity(url+"/add/score", scoreBoard, ScoreBoard.class );
    return responseEntity.getBody();

}

型号:-

public class ScoreBoard {

    private long id;
    private String team;
    private int point;

    public ScoreBoard(){

    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTeam() {
        return team;
    }

    public void setTeam(String team) {
        this.team = team;
    }

    public int getPoint() {
        return point;
    }

    public void setPoint(int point) {
        this.point = point;
    }
}

我试着用Postman测试了一下,正文如下:-。http:/localhost:8080addscore。 (POST)

{
    "id": 1,
    "team": "new team",
    "point": 3030
}

我得到了以下错误。

2020-06-10 21:19:17.303 ERROR 19926 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.RestClientException: Error while extracting response for type [class com.example.resttemplatedemo.model.ScoreBoard] and content type [application/json]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'ScoreBoard': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'ScoreBoard': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
 at [Source: (PushbackInputStream); line: 1, column: 12]] with root cause

com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'ScoreBoard': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
 at [Source: (PushbackInputStream); line: 1, column: 12]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1851) ~[jackson-core-2.11.0.jar:2.11.0]
java json spring spring-boot post
1个回答
0
投票

为了将JSON HTTP请求体反序列化到你的类中,ScoreBoard必须有一个没有参数的构造函数。

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