Jackson Mapper post-construct

Brandon Yarbrough picture Brandon Yarbrough · Jul 26, 2011 · Viewed 15.7k times · Source

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.

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.

Answer

Mike Rylander picture Mike Rylander · Nov 28, 2016

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

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