在过去的几个小时里,我阅读了许多 StackOverflow 问题和文章,但没有任何建议有帮助。我尝试了什么:
- 将 @JsonCreator 和 @JsonProperty 添加到Person和Employee类(链接)
- 将 @JsonDeserialize(using = EmployeeDeserialize.class) 添加到Employee类(链接)
- 将 Lombok 添加为依赖项,设置lombok.anyConstructor.addConstructorProperties=true并将 @Data / @Value 注释添加到Person和Employee类(链接)
最后,我手动进行了反序列化:
String json = "{\"name\": \"Unknown\",\"email\": \"please@work.now\",\"salary\":1}"; ObjectMapper objectMapper = new ObjectMapper(); Employee employee = objectMapper.readValue(json, Employee.class);
通过这种方式,我可以反序列化 JSON,但是一旦我开始我的 spring-boot-starter-web 项目并调用
http://localhost:8080/print?name=unknown&email=please@work.now&salary=1
我得到了很好的旧 BeanInstantiationException
Failed to instantiate [Employee]: No default constructor found
我没有主意了。当我手动进行反序列化时,有人知道为什么这会起作用吗?为什么当我调用 REST 端点时它会抛出异常?
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
public class EmployeeController {
@GetMapping("print")
public void print(Employee employee) {
System.out.println(employee);
}
}
public class Person {
private final String name;
@JsonCreator
public Person(@JsonProperty("name") String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Employee extends Person {
private final String email;
private final int salary;
@JsonCreator
public Employee(
@JsonProperty("name") String name,
@JsonProperty("email") String email,
@JsonProperty("salary") int salary) {
super(name);
this.email = email;
this.salary = salary;
}
public String getEmail() {
return email;
}
public int getSalary() {
return salary;
}
}