2

Is there any way of programatically telling jackson to ignore a property? For instance, by name.

My problem is that I'm serializing third party objects, some of which have parent/child cyclic dependencies that cause

com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError)

Because I can't modify the code, the usual ways of breaking cyclic dependencies don't work for me.

I'm using an ObjectMapper and ObjectWriter:

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setVisibility(new VisibilityChecker.Std(JsonAutoDetect.Visibility.ANY));
writer = mapper.writerWithDefaultPrettyPrinter();
writer.writeValueAsString(object);

And I know they're highly customizable, as with the serialization inclusion and visibility that I have in the snippet, but I can't find they way of achieving something like

mapper.ignoreProperty("parent");
Community
  • 1
  • 1
user3748908
  • 885
  • 2
  • 9
  • 26

1 Answers1

5

You should use Jackson's Mix-In Annotations to break the cyclic dependency:

objectMapper.getSerializationConfig().addMixInAnnotations(ClassWithParent.class, SuppressParentMixIn.class);

And then define SuppressParentMixIn:

public interface SuppressParentMixIn {

    @JsonIgnore
    public ParentClass getParent();

}

This allows you to programmatically insert annotations on classes that you don't control. Whenever Jackson goes to serialize ClassWithParent, it will behave as if all the annotations from SuppressParentMixIn were applied to ClassWithParent.

Darth Android
  • 3,437
  • 18
  • 19
  • Thanks, that is very likely what I'm looking for. However, it doesn't work. I've gone twenty times over the names of the properties, but there still has to be something that I'm missing. – user3748908 Mar 18 '16 at 15:48