[英]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.