2

有没有办法以编程方式告诉杰克逊忽略一个属性?例如,按名称。

我的问题是我正在序列化第三方对象,其中一些具有父/子循环依赖关系,导致

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

因为我不能修改代码,所以打破循环依赖的常用方法对我不起作用。

我正在使用ObjectMapperand 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);

而且我知道它们是高度可定制的,就像我在片段中的序列化包含和可见性一样,但我找不到他们实现类似的方法

mapper.ignoreProperty("parent");
4

1 回答 1

5

您应该使用 Jackson 的Mix-In Annotations来打破循环依赖:

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

然后定义SuppressParentMixIn

public interface SuppressParentMixIn {

    @JsonIgnore
    public ParentClass getParent();

}

这允许您以编程方式在您无法控制的类上插入注释。每当 Jackson 进行序列化ClassWithParent时,它的行为就好像所有注释SuppressParentMixIn都已应用于ClassWithParent.

于 2016-03-18T15:10:08.557 回答