假设我有一个学生实体:
@Entity
public class Student {
@Getter
@JsonProperty
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Getter
@JsonProperty
@ManyToOne
private Clazz clazz;
@Getter
@JsonProperty
private String
firstName,
lastName;
}
我想通过POST到JAX-RS类来坚持它:
@Path("/student")
@Produces(MediaType.APPLICATION_JSON)
public class StudentResource {
private StudentDAO studentDao;
public StudentResource(StudentDAO studentDao) {
this.studentDao = studentDao;
}
@POST
@UnitOfWork
@Consumes(MediaType.APPLICATION_JSON)
public void persist(Student student) {
this.studentDao.save(student);
}
}
我的请求正文如下:
{
"firstName": "Joe",
"lastName": "Bloggs",
"clazz": 1
}
然后杰克逊会爆发,因为:
DEBUG [2015-05-16 11:08:59,144] io.dropwizard.jersey.jackson.JsonProcessingExceptionMapper: Unable to process JSON
! com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class Clazz] from Integral number (1); no single-int-arg constructor/factory method
我理解为什么我收到此错误;它无法从密钥反序列化Clazz对象。我无法想出一些修复此问题的hacky方法(例如,添加一个Clazz(int id)构造函数并使clazzDao静态可用)。但有人能为我提供更清洁的解决方案吗?提前谢谢。
答案 0 :(得分:0)
正如Ryan Kennedy在dropwizard邮件列表中指出的那样,显而易见的解决方案是不要像在持久层中那样使用与REST相同的dto样式对象。然后,在StudentResource中接收REST对象并转换为我可以持久化的REST对象是微不足道的。