Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson object mapper how to ignore JsonProperty annotation?

Tags:

java

jackson

I have the following scenario:

public class A {

    @JsonProperty("member")
    private Integer Member;
}

public class B {

    private Integer Member;
}

Now, I wish to do the following:

ObjectMapper mapper = new ObjectMapper();
B b = new B(); b.setMember(1);

A a = mapper.converValue(b, A.class);

Ordinarily, this would work. However, since the objectMapper takes annotations such as @JsonProperty into account, I get the following result:

A.getMember(); // Member = NULL

There is a workaround, where all fields that are expected to be null due to this are set manually, i.e. A.setMember(b.getMember());, but this defeats the purpose of using the objectMapper in the first place and is potentially error-prone.

Is there a way to configure the objectMapper to ignore the @JsonProperty fields of a given class (or globally)?

like image 718
filpa Avatar asked Aug 15 '17 13:08

filpa


2 Answers

To ignore all annotations the syntax in Jackson version 2.x is:

objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false)

Just ignoring a subset seems to be not possible with this approach.

But a much better solution can be found in this answer: https://stackoverflow.com/a/55064740/3351474

For your needs it should be then:

public static class IgnoreJacksonPropertyName extends JacksonAnnotationIntrospector {
  @Override
  protected <A extends Annotation> A _findAnnotation(Annotated annotated, Class<A> annoClass) {
    if (annoClass == JsonProperty.class) {
      return null;
    }
    return super._findAnnotation(annotated, annoClass);
  }
}

...

mapper.setAnnotationIntrospector(new IgnoreJacksonPropertyName());
like image 127
k_o_ Avatar answered Oct 18 '22 01:10

k_o_


You can configure the ObjectMapper to ignore annotations like @JsonProperty by doing:

ObjectMapper objectMapper = new ObjectMapper().configure(
             org.codehaus.jackson.map.DeserializationConfig.Feature.USE_ANNOTATIONS, false)
                .configure(org.codehaus.jackson.map.SerializationConfig.Feature.USE_ANNOTATIONS, false)

But this will cause it to also ignore things like @JsonIgnore etc. I'm not aware of any way to make the ObjectMapper ignore only specific annotations.

like image 33
Plog Avatar answered Oct 18 '22 01:10

Plog