没有默认构造函数

时间:2018-03-09 22:10:03

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

在过去的几个小时里,我阅读了许多StackOverflow问题和文章,但没有任何建议有帮助。我尝试了什么:

  • 将@JsonCreator和@JsonProperty添加到 Person Employee 类(link
  • 将@JsonDeserialize(使用= EmployeeDeserialize.class)添加到员工类(link
  • 将Lombok添加为依赖项,设置 lombok.anyConstructor.addConstructorProperties = true 并将@Data / @Value注释添加到 Person Employee 课程(link
  • 最后,我手动进行了反序列化:

    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

我没有想法。当我手动进行反序列化时,anybod知道为什么会这样吗?当我调用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;
    }
}

1 个答案:

答案 0 :(得分:0)

您正在实施JSON反序列化,但您没有使用任何JSON。

更改为在控制器方法上使用@PostMapping并使用Postman或cURL之类的东西将JSON发送到/ print端点。