我正在使用 Jackson ObjectMapper
将一些 JSON 反序列化为 Java 类,我们将其称为 PlayerData
。我想在 PlayerData
类中添加一些逻辑,以在加载字段后修复一些数据。例如,一些早期的 JSON 文件使用“sex”标志而不是一个“性别”标志,所以如果设置了性别标志但没有设置性别标志,我想将性别字段的值设置为性别字段的值。
是否有某种@PostConstruct 或@AfterLoad 注释可以附加到方法上?或者也许是我可以实现的接口(interface)?我没有注意到文档中有一个,但它似乎是一个明显的功能。
最佳答案
通过 link 找到这个在评论中(信用:fedor.belov)。这似乎允许您运行代码后构造。
Adding a comment for people who end up here via http://jira.codehaus.org/browse/JACKSON-645 or http://jira.codehaus.org/browse/JACKSON-538 and are looking for a method which is called after a deserializer completes. I was able to achieve the desired effect by including an annotation and writing a converter which uses the same class as input and output.
@JsonDeserialize(converter=MyClassSanitizer.class) // invoked after class is fully deserialized
public class MyClass {
public String field1;
}
import com.fasterxml.jackson.databind.util.StdConverter;
public class MyClassSanitizer extends StdConverter<MyClass,MyClass> {
@Override
public MyClass convert(MyClass var1) {
var1.field1 = munge(var1.field1);
return var1;
}
}
关于java - Jackson Mapper 后期制作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6834677/