在我在Spring Boot中构建的REST端点中,我试图将vehicleDTO
传递给 Controller 。但是在到达我的 Controller 之前,有一个错误。
载具DTO
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.myvehicle.EngineType;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class VehicleDTO {
@JsonIgnore
private Long id;
@NotNull(message = "vehiclenumber can not be null!")
private String vehiclenumber;
@Min(2)
@NotNull(message = "Seat count can not be less than 2!")
private Integer vehicleseatcount;
@NotNull(message = "Engine Type can not be null!")
private EngineType enginetype;
@Max(5)
private Integer vehiclerating;
private VehicleDTO(Long id, String vehiclenumber, Integer vehicleseatcount, EngineType enginetype,Integer vehiclerating){
this.vehiclenumber=vehiclenumber;
this.vehicleseatcount=vehicleseatcount;
this.enginetype=enginetype;
this.vehiclerating=vehiclerating;
this.id=id;
}
public static VehicleDTOBuilder newBuilder()
{
return new VehicleDTOBuilder();
}
@JsonProperty
public Long getId() {
return id;
}
public String getvehiclenumber() {
return vehiclenumber;
}
public Integer getvehicleseatcount() {
return vehicleseatcount;
}
public EngineType getEnginetype() {
return enginetype;
}
public Integer getvehiclerating() {
return vehiclerating;
}
public static class VehicleDTOBuilder{
private Long id;
private String vehiclenumber;
private Integer vehicleseatcount;
private EngineType enginetype;
private Integer vehiclerating;
public VehicleDTOBuilder setId(Long id) {
this.id = id;
return this;
}
public VehicleDTOBuilder setvehiclenumber(String vehiclenumber) {
this.vehiclenumber = vehiclenumber;
return this;
}
public VehicleDTOBuilder setvehicleseatcount(Integer vehicleseatcount) {
this.vehicleseatcount = vehicleseatcount;
return this;
}
public VehicleDTOBuilder setEnginetype(EngineType enginetype) {
this.enginetype = enginetype;
return this;
}
public VehicleDTOBuilder setvehiclerating(Integer vehiclerating) {
this.vehiclerating = vehiclerating;
return this;
}
public VehicleDTO createVehicleDTO()
{
return new VehicleDTO(id, vehiclenumber, vehicleseatcount, enginetype,vehiclerating);
}
}
}
我的DTO具有一个称为EngineType的枚举类型
public enum EngineType {
ELECTRIC, DIESEL
}
我的 Controller 看起来像这样
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public VehicleDTO addvehicle(@Valid @RequestBody VehicleDTO vehicleDTO)
{
VehicleDO vehicleDO = Mapper.VehicleDO(vehicleDTO);
return Mapper.makeVehicleDTO(Service.addvehicle(vehicleDO));
}
最佳答案
此异常:
意味着Jackson找不到实例化VehicleDTO
的方法,该方法是默认构造函数(无arg构造函数)或JsonCreator
。
在使用构建器模式时,您将配置VehicleDTO
类,使Jackson可以使用VehicleDTO
实例化VehicleDTOBuilder
,例如:
@JsonDeserialize(builder = VehicleDTO.VehicleDTOBuilder.class)
public class VehicleDTO {
...
}
并用JsonPOJOBuilder注释您的构建器为:
@JsonPOJOBuilder(buildMethodName = "createVehicleDTO", withPrefix = "set")
public static class VehicleDTOBuilder{
...
}
根据javadoc,
JsonPOJOBuilder
是: