Spring: Type definition error when posting a new object using a REST service

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:

"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]",

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";

}
akortex91 :

You'll need an empty constructor to allow for Jackson to perform it's deserialization actions correctly.

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.

This way you'll be more flexible and you'll not be binding you transfer objects to the actual entity models.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=475338&siteId=1