【发布时间】:2011-12-08 12:49:03
【问题描述】:
假设我有以下课程:
public class Person {
String name;
Set<Department> departments;
}
public class Department {
String code;
String name;
}
所以我想编写一个自定义的部门反序列化器,以便注释 Person 类中的 deparments 字段以使用它。因为此自定义反序列化器将仅用于反序列化 Person 对象内的 Department 对象。问题是我的自定义部门反序列化器需要有一个必须在反序列化器的构造函数中传递的 DepartmentRepository。我怎样才能做到这一点?这可能吗?我不想在对象映射器中注册反序列化器,因为它只能在 Person 类的 deparatments 字段被反序列化时使用。
更新:我需要的是,除了使用参数 contentUsing = MyCustomDepartmentDeserializer.class 使用 JsonDeserialize 注释对部门字段进行注释之外,这是一种告诉杰克逊,当它创建 MyCustomDepartmentDeserializer 对象时,它必须通过调用接收 DepartmentRepository 的构造函数来完成。反序列化器可能是这样的:
public class MyCustomDepartmentDeserializer extends JsonDeserializer<Department> {
private final DepartmentRepository departmentRepository;
public MyCustomDepartmentDeserializer(DepartmentRepository departmentRepository) {
this.departmentRepository = departmentRepository;
}
@Override
public Department deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
//IMPLEMENTATION!
}
}
【问题讨论】:
标签: java deserialization jackson