春季启动消耗Web服务

时间:2020-04-24 13:19:24

标签: spring-boot web-services

我有一个这样构造的Web服务

@RestController
public class GreetingController {

    @PostMapping(path = "/greetingws")
    public Foo greeting(@RequestBody Foo dto) {
        return dto;
    }
}

当我使用网络服务时,我会这样

Foo f = new Foo("kkkkk");

ResponseEntity<String> t2 = restTemplate
          .exchange("http://localhost:8080/greetingws", HttpMethod.POST, new HttpEntity<Foo>(f), String.class);

但是它返回错误:

org.springframework.web.client.HttpClientErrorException$BadRequest: 400 : [{"timestamp":"2020-04-24T13:03:30.191+0000","status":400,"error":"Bad Request","message":"JSON parse error: Cannot construct instance of it.test.demo.controller.Foo (although at least one C... (7991 bytes)]

我的Foo类如下:

public class Foo {

    private String nome;

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Foo(String nome) {
        super();
        this.nome = nome;
    }

    @Override
    public String toString() {
        return "Foo [nome=" + nome + "]";
    }

}

我在哪里出错?

1 个答案:

答案 0 :(得分:1)

Come Romeo:-)

您似乎缺少Foo中的默认构造函数,而Spring无法反序列化请求。
添加:

public Foo() {
}