杰克逊·马珀(Jackson Mapper)建后 [英] Jackson Mapper post-construct

查看:108
本文介绍了杰克逊·马珀(Jackson Mapper)建后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jackson ObjectMapper将一些JSON反序列化为Java类,我们将其称为PlayerData.我想在PlayerData类中添加一些逻辑,以在装入字段之后修正一些数据.例如,一些早期的JSON文件曾经使用性别"标志代替性别"标志,因此,如果设置了性别标志,但未设置性别标志,我想将性别字段的值设置为性别字段的值.

I am using the Jackson ObjectMapper to deserialize some JSON into a Java class, which we'll call PlayerData. I would like to add a bit of logic to the PlayerData class to fix up some data after the fields have been loaded in. For example, some early JSON files used to use a "sex" flag instead of a "gender" falg, so if the sex flag is set but the gender flag is not set, I'd like to set the value of the gender field to be the value of the sex field.

我可以在方法上粘贴某种@PostConstruct或@AfterLoad注释吗?还是我可以实现的接口?我没有在文档中注意到一个,但这似乎是一个明显的功能.

Is there some sort of @PostConstruct or @AfterLoad annotation that I could affix to a method? Or perhaps an interface that I could implement? I didn't notice one in the documentation, but it seemed like an obvious feature.

推荐答案

通过链接(来源: fedor.belov ).这似乎允许您运行代码后构造.

Found this thru a link in the comments (credit: fedor.belov). This appears to allow you to run code post construct.

为通过此处到达此处的人添加评论 http://jira.codehaus.org/browse/JACKSON-645 http://jira.codehaus.org/browse/JACKSON-538 ,并且正在寻找一种 解串器完成后调用的方法.我以前可以 通过添加注释并编写一个 转换器使用与输入和输出相同的类.

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

这篇关于杰克逊·马珀(Jackson Mapper)建后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆