Ignore properties marked with specific annotation

Viewed 671

I have ObjectMapper instance:

ObjectMapper mapper = new ObjectMapper();

In runtime want to serialize instance of class. What is the class the program doesn't known. It's object instance of parameterized type T.

How to ignore all properties (fields and getters) which marked specified annotation (javax.persistence.Id) ?

Example:

public static class PojoTest {
   @Id
   public String idTest;
   public String id;
}
    
public void serialize(Object object) {
   ObjectMapper objectMapper = new ObjectMapper();
   // TODO ignore property mark @Id annotation
   Map<Object, Object> map = objectMapper.convertValue(object, Map.class);
   assertFalse(map.containsKey("idTest"));
}

public void test() {
  PojoTest pojoTest = new PojoTest();
  pojoTest.id = "foo";
  pojoTest.idTest = "bar";
  serialize(pojoTest);
}
1 Answers

You can implement a new com.fasterxml.jackson.databind.AnnotationIntrospector class where you can extend hasIgnoreMarker method:

static class IdIgnoreAnnotationIntrospector extends AnnotationIntrospector {
    @Override
    public Version version() {
        return new Version(1,0,0,"Ignore @Id", "group.id", "artifact.id");
    }

    @Override
    public boolean hasIgnoreMarker(AnnotatedMember m) {
        return hasIdAnnotation(m);
    }

    boolean hasIdAnnotation(AnnotatedMember member) {
        return member.getAnnotation(Id.class) != null;
    }
}

Now you need to register this introspector:

ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(new JacksonAnnotationIntrospector(), new IdIgnoreAnnotationIntrospector()));

Now you can ignore all fields marked with @Id annotation.

Related