[英]How to ignore certain fields with Jackson's ObjectMapper.readerForUpdating
[英]Jackson ObjectMapper: How to omit (ignore) fields of certain type from serialization?
我如何告诉 Jackson ObjectMapper 忽略某些类型(类)的字段,在我的Object.class
的情况下,从序列化?
约束:
为了提供帮助,下面是一个单元测试,期望从序列化中忽略字段objectsList
和objectField
,但它的方法不正确,它是按名称而不是按类型过滤它们。
public static class FavoriteShows {
public Simpsons favorite = new Simpsons();
public BigBangTheory preferred = new BigBangTheory();
}
public static class Simpsons {
public String title = "The Simpsons";
public List<Object> objectsList = List.of("homer", "simpson");
public Object objectField = new HashMap() {{
put("mr", "burns");
put("ned", "flanders");
}};
}
public static class BigBangTheory {
public String title = "The Big Bang Theory";
public List<Object> objectsList = List.of("sheldon", "cooper");
public Object objectField = new HashMap() {{
put("leonard", "hofstadter");
put("Raj", "koothrappali");
}};
}
public abstract static class MyMixIn {
@JsonIgnore
private Object objectField;
@JsonIgnore
private Object objectsList;
}
@Test
public void test() throws JsonProcessingException {
// GIVEN
// Right solution must work for any (MixIn(s) is out of questions) Jackson annotated class
// without its modification.
final ObjectMapper mapper = new ObjectMapper()
.addMixIn(Simpsons.class, MyMixIn.class)
.addMixIn(BigBangTheory.class, MyMixIn.class);
// WHEN
String actual = mapper.writeValueAsString(new FavoriteShows());
System.out.println(actual);
// THEN
// Expected: {"favorite":{"title":"The Simpsons"},"preferred":{"title":"The Big Bang Theory"}}
assertThat(actual).isEqualTo("{\"favorite\":{\"title\":\"The Simpsons\"},\"preferred\":{\"title\":\"The Big Bang Theory\"}}");
}
一种方法是使用自定义AnnotationIntrospector
。
class A {
int three = 3;
int four = 4;
B b = new B();
// setters + getters
}
class B {
int one = 1;
int two = 2;
// setters + getters
}
忽略所有类型为B
的字段:
ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
@Override
protected boolean _isIgnorable(Annotated a) {
return super._isIgnorable(a)
// Ignore B.class
|| a.getRawType() == B.class
// Ignore List<B>
|| a.getType() == TypeFactory.defaultInstance()
.constructCollectionLikeType(List.class, B.class);
}
});
String json = mapper.writeValueAsString(new A());
如果您使用的是 mixins,您应该能够使用 @JsonIgnoreType 进行注释以使其忽略 class。 docs供参考全局忽略 Jackson 中的 class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.