我有一个对象,它通过 json POST 请求获取两个参数以在数据库中创建新条目,但出现此错误:
"Type definition error: [simple type, class ffuentese.rest_example.Persona]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of
ffuentese.rest_example.Persona
(no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator) at [Source: (PushbackInputStream); line: 2, column: 3]",
这是对象:
@Entity
public class Persona {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String nombre;
private String apellido;
public Persona(String nombre, String apellido) {
this.nombre = nombre;
this.apellido = apellido;
}
public Integer getId() {
return id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
}
这是 Controller 方法:
@PostMapping(path="/persona")
public @ResponseBody String addPersona(@RequestBody Persona p) {
personaRepository.save(p);
return "success";
}
最佳答案
您需要一个空的构造函数来允许 Jackson 正确执行其反序列化操作。
此外,使用实体模型作为数据传输对象并不是一个好主意。我建议创建一个 PersonaDto
,其中包含构建对象所需的所有字段,并使用 Spring converter
将其转换为 Persona
对象。
这样您将更加灵活,并且不会将对象传输绑定(bind)到实际的实体模型。
关于java - Spring:使用 REST 服务发布新对象时出现类型定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51014320/