Java Spring:使用 REST 服务发布新对象时出现类型定义错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51014320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring: Type definition error when posting a new object using a REST service
提问by ffuentes
I have an object which gets two parameters through a json POST request to create a new entry in the database and I get this error:
我有一个对象,它通过 json POST 请求获取两个参数以在数据库中创建一个新条目,但出现此错误:
"Type definition error: [simple type, class ffuentese.rest_example.Persona]; nested exception is com.fasterxml.Hymanson.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]",
“类型定义错误:[简单类型,类 ffuentese.rest_example.Persona];嵌套异常是 com.fasterxml.Hymanson.databind.exc.InvalidDefinitionException:无法构造实例
ffuentese.rest_example.Persona
(没有创建者,如默认构造,存在):无法反序列化[Source: (PushbackInputStream); line: 2, column: 3]",
This is the object:
这是对象:
@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;
}
}
This is the controller method:
这是控制器方法:
@PostMapping(path="/persona")
public @ResponseBody String addPersona(@RequestBody Persona p) {
personaRepository.save(p);
return "success";
}
采纳答案by akortex91
You'll need an empty constructor to allow for Hymanson to perform it's deserialization actions correctly.
您将需要一个空的构造函数以允许 Hymanson 正确执行它的反序列化操作。
Moreover though, using the entity model as a data transfer object is not a good idea. I would suggest to create a PersonaDto
which will contain all the fields you'll require to construct for object and the use a Spring converter
to convert it over to a Persona
object.
此外,使用实体模型作为数据传输对象并不是一个好主意。我建议创建一个PersonaDto
包含您需要为对象构造的所有字段并使用 Springconverter
将其转换为对象的字段Persona
。
This way you'll be more flexible and you'll not be binding you transfer objects to the actual entity models.
这样,您将更加灵活,并且不会绑定您将对象传输到实际实体模型。