use*_*908 2 java json cyclic-reference jackson
有没有办法以编程方式告诉杰克逊忽略财产?例如,按名称.
我的问题是我正在序列化第三方对象,其中一些具有导致的父/子循环依赖
com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError)
Run Code Online (Sandbox Code Playgroud)
因为我无法修改代码,所以打破循环依赖关系的常用方法对我来说不起作用.
我正在使用ObjectMapper和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);
Run Code Online (Sandbox Code Playgroud)
而且我知道它们是高度可定制的,就像我在代码片段中包含的序列化包含和可见性一样,但我找不到它们实现类似内容的方式
mapper.ignoreProperty("parent");
Run Code Online (Sandbox Code Playgroud)
您应该使用Jackson的Mix-In Annotations来打破循环依赖:
objectMapper.getSerializationConfig().addMixInAnnotations(ClassWithParent.class, SuppressParentMixIn.class);
Run Code Online (Sandbox Code Playgroud)
然后定义SuppressParentMixIn:
public interface SuppressParentMixIn {
@JsonIgnore
public ParentClass getParent();
}
Run Code Online (Sandbox Code Playgroud)
这允许您以编程方式在不受控制的类上插入注释.每当杰克逊进行序列化时ClassWithParent,它的行为就像SuppressParentMixIn应用了所有注释一样ClassWithParent.